multiCMD 1.66__tar.gz → 1.68__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {multicmd-1.66/multiCMD.egg-info → multicmd-1.68}/PKG-INFO +33 -4
  2. multicmd-1.66/PKG-INFO → multicmd-1.68/README.md +31 -27
  3. multicmd-1.66/README.md → multicmd-1.68/multiCMD.egg-info/PKG-INFO +56 -1
  4. {multicmd-1.66 → multicmd-1.68}/multiCMD.egg-info/SOURCES.txt +1 -0
  5. {multicmd-1.66 → multicmd-1.68}/multiCMD.py +95 -35
  6. multicmd-1.68/setup.py +41 -0
  7. {multicmd-1.66 → multicmd-1.68}/tests/test_helpers.py +65 -4
  8. multicmd-1.68/tests/test_terminal_width.py +377 -0
  9. multicmd-1.66/setup.py +0 -31
  10. {multicmd-1.66 → multicmd-1.68}/LICENSE +0 -0
  11. {multicmd-1.66 → multicmd-1.68}/multiCMD.egg-info/dependency_links.txt +0 -0
  12. {multicmd-1.66 → multicmd-1.68}/multiCMD.egg-info/entry_points.txt +0 -0
  13. {multicmd-1.66 → multicmd-1.68}/multiCMD.egg-info/top_level.txt +0 -0
  14. {multicmd-1.66 → multicmd-1.68}/scripts/multiCMD +0 -0
  15. {multicmd-1.66 → multicmd-1.68}/setup.cfg +0 -0
  16. {multicmd-1.66 → multicmd-1.68}/tests/test_api.py +0 -0
  17. {multicmd-1.66 → multicmd-1.68}/tests/test_async_executor.py +0 -0
  18. {multicmd-1.66 → multicmd-1.68}/tests/test_cli.py +0 -0
  19. {multicmd-1.66 → multicmd-1.68}/tests/test_cli_closed_stdout.py +0 -0
  20. {multicmd-1.66 → multicmd-1.68}/tests/test_cli_failed_stdout.py +0 -0
  21. {multicmd-1.66 → multicmd-1.68}/tests/test_cli_input.py +0 -0
  22. {multicmd-1.66 → multicmd-1.68}/tests/test_cli_summary.py +0 -0
  23. {multicmd-1.66 → multicmd-1.68}/tests/test_display.py +0 -0
  24. {multicmd-1.66 → multicmd-1.68}/tests/test_embed.py +0 -0
  25. {multicmd-1.66 → multicmd-1.68}/tests/test_env.py +0 -0
  26. {multicmd-1.66 → multicmd-1.68}/tests/test_expand_ranges.py +0 -0
  27. {multicmd-1.66 → multicmd-1.68}/tests/test_handover.py +0 -0
  28. {multicmd-1.66 → multicmd-1.68}/tests/test_interrupts.py +0 -0
  29. {multicmd-1.66 → multicmd-1.68}/tests/test_packaging.py +0 -0
  30. {multicmd-1.66 → multicmd-1.68}/tests/test_parsing.py +0 -0
  31. {multicmd-1.66 → multicmd-1.68}/tests/test_pass_fds.py +0 -0
  32. {multicmd-1.66 → multicmd-1.68}/tests/test_ping.py +0 -0
  33. {multicmd-1.66 → multicmd-1.68}/tests/test_pool.py +0 -0
  34. {multicmd-1.66 → multicmd-1.68}/tests/test_process_groups.py +0 -0
  35. {multicmd-1.66 → multicmd-1.68}/tests/test_pty.py +0 -0
  36. {multicmd-1.66 → multicmd-1.68}/tests/test_reader.py +0 -0
  37. {multicmd-1.66 → multicmd-1.68}/tests/test_reader_quit.py +0 -0
  38. {multicmd-1.66 → multicmd-1.68}/tests/test_regressions.py +0 -0
  39. {multicmd-1.66 → multicmd-1.68}/tests/test_run_command.py +0 -0
  40. {multicmd-1.66 → multicmd-1.68}/tests/test_run_commands.py +0 -0
  41. {multicmd-1.66 → multicmd-1.68}/tests/test_sudo.py +0 -0
  42. {multicmd-1.66 → multicmd-1.68}/tests/test_supervision.py +0 -0
  43. {multicmd-1.66 → multicmd-1.68}/tests/test_task.py +0 -0
  44. {multicmd-1.66 → multicmd-1.68}/tests/test_windows.py +0 -0
@@ -1,13 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.66
3
+ Version: 1.68
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
7
7
  Author-email: pan@zopyr.us
8
- License: GPLv3+
8
+ License-Expression: GPL-3.0-or-later
9
9
  Classifier: Programming Language :: Python :: 3
10
- Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
11
10
  Classifier: Operating System :: POSIX :: Linux
12
11
  Classifier: Operating System :: Microsoft :: Windows
13
12
  Requires-Python: >=3.6
@@ -19,8 +18,8 @@ Dynamic: classifier
19
18
  Dynamic: description
20
19
  Dynamic: description-content-type
21
20
  Dynamic: home-page
22
- Dynamic: license
23
21
  Dynamic: license-file
22
+ Dynamic: license-expression
24
23
  Dynamic: requires-python
25
24
  Dynamic: summary
26
25
 
@@ -559,6 +558,36 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
558
 
560
559
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
561
560
 
561
+ ## Upgrading to 1.68 from 1.67
562
+
563
+ - Nothing needs doing.
564
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
565
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
566
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
567
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
568
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
569
+ was 20 columns by 0 rows).
570
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
571
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
572
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
573
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
574
+ than the width (1.67: the full width, and never cut).
575
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
576
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
577
+ more than 1.67's.
578
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
579
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
580
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
581
+
582
+ ## Upgrading to 1.67 from 1.66
583
+
584
+ - Nothing needs doing. `mcmd` is unchanged.
585
+ - Fix, library: `format_bytes()` counts a size string in whole bytes: `'4.1G'` is 4100000000 (1.66: 4099999999, from a
586
+ float). hpcp's size options (`-L`, `-F`, `-dis`, `-ddr`) take these values with 1.67.
587
+ - Fix, library: `format_bytes()` shows a size of 1000 Y or more in Y, as `'1000.00 Y'` or `'1024.00 Yi'` (1.66: `KeyError`),
588
+ and `float('inf')` as `'inf Yi'` (1.66: it never returned).
589
+ - Packaging: built with setuptools 77 or later, the metadata names the license as `License-Expression: GPL-3.0-or-later`.
590
+
562
591
  ## Upgrading to 1.66 from 1.65
563
592
 
564
593
  - Nothing needs doing for `mcmd`, which is unchanged, nor for hpcp 9.92, which checks its sizes itself. hpcp up to 9.91
@@ -1,29 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: multiCMD
3
- Version: 1.66
4
- Summary: Run commands simultaneously
5
- Home-page: https://github.com/yufei-pan/multiCMD
6
- Author: Yufei Pan
7
- Author-email: pan@zopyr.us
8
- License: GPLv3+
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
11
- Classifier: Operating System :: POSIX :: Linux
12
- Classifier: Operating System :: Microsoft :: Windows
13
- Requires-Python: >=3.6
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Dynamic: author
17
- Dynamic: author-email
18
- Dynamic: classifier
19
- Dynamic: description
20
- Dynamic: description-content-type
21
- Dynamic: home-page
22
- Dynamic: license
23
- Dynamic: license-file
24
- Dynamic: requires-python
25
- Dynamic: summary
26
-
27
1
  # multiCMD
28
2
 
29
3
  Run many commands at the same time — from the shell or from Python.
@@ -559,6 +533,36 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
533
 
560
534
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
561
535
 
536
+ ## Upgrading to 1.68 from 1.67
537
+
538
+ - Nothing needs doing.
539
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
540
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
541
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
542
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
543
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
544
+ was 20 columns by 0 rows).
545
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
546
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
547
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
548
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
549
+ than the width (1.67: the full width, and never cut).
550
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
551
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
552
+ more than 1.67's.
553
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
554
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
555
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
556
+
557
+ ## Upgrading to 1.67 from 1.66
558
+
559
+ - Nothing needs doing. `mcmd` is unchanged.
560
+ - Fix, library: `format_bytes()` counts a size string in whole bytes: `'4.1G'` is 4100000000 (1.66: 4099999999, from a
561
+ float). hpcp's size options (`-L`, `-F`, `-dis`, `-ddr`) take these values with 1.67.
562
+ - Fix, library: `format_bytes()` shows a size of 1000 Y or more in Y, as `'1000.00 Y'` or `'1024.00 Yi'` (1.66: `KeyError`),
563
+ and `float('inf')` as `'inf Yi'` (1.66: it never returned).
564
+ - Packaging: built with setuptools 77 or later, the metadata names the license as `License-Expression: GPL-3.0-or-later`.
565
+
562
566
  ## Upgrading to 1.66 from 1.65
563
567
 
564
568
  - Nothing needs doing for `mcmd`, which is unchanged, nor for hpcp 9.92, which checks its sizes itself. hpcp up to 9.91
@@ -847,4 +851,4 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
847
851
  ## License
848
852
 
849
853
  GPLv3+ — see the package metadata. Authored by Yufei Pan (<pan@zopyr.us>).
850
- ```
854
+ ```
@@ -1,3 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: multiCMD
3
+ Version: 1.68
4
+ Summary: Run commands simultaneously
5
+ Home-page: https://github.com/yufei-pan/multiCMD
6
+ Author: Yufei Pan
7
+ Author-email: pan@zopyr.us
8
+ License-Expression: GPL-3.0-or-later
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: author
16
+ Dynamic: author-email
17
+ Dynamic: classifier
18
+ Dynamic: description
19
+ Dynamic: description-content-type
20
+ Dynamic: home-page
21
+ Dynamic: license-file
22
+ Dynamic: license-expression
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
1
26
  # multiCMD
2
27
 
3
28
  Run many commands at the same time — from the shell or from Python.
@@ -533,6 +558,36 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
533
558
 
534
559
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
535
560
 
561
+ ## Upgrading to 1.68 from 1.67
562
+
563
+ - Nothing needs doing.
564
+ - Fix: a terminal that reports no size (0 columns: a pty nobody sized, as `script` makes without a terminal of its own,
565
+ some CI runners) does not know its size. `get_terminal_size()` gives `COLUMNS` / `LINES`, else 80x24,
566
+ what other programs take such a terminal for (no terminal at all: 240x50, as before). A progress bar stays on one line,
567
+ `mcmd`'s summary table has room, and a pty-mode command's window is 80x24, less the `[#]` prefix when commands run at
568
+ once (1.67: each frame of a bar with a total took six lines, the table was cut to its headings' widths, and the window
569
+ was 20 columns by 0 rows).
570
+ - Changed, library: a `print_progress_bar()` frame fits in one column less than the terminal, counted in display columns
571
+ (a wide character takes two, an East Asian ambiguous character one), so it does not wrap and scroll a row per frame.
572
+ Without a total, the prefix gives way first, from its start, then the end of the line, a whole field at a time, so a
573
+ number keeps its label and its unit (`Size: 1.15 GiB` stays or goes whole). That frame is padded to one column less
574
+ than the width (1.67: the full width, and never cut).
575
+ - Changed, library: the frame at the total is as wide as the frames before it (a full bar is one block wider), so the
576
+ line keeps no character of the frame before it (`| 00:00:001` for `| 00:00:00`). On a pipe the 100% frame has one block
577
+ more than 1.67's.
578
+ - Known, planned for 1.69 ([docs/limitations.md](docs/limitations.md)): a bar past its total never ends its line; a tab or
579
+ newline in a frame's prefix or suffix breaks the frame over several lines; and a bar with a total drops its percent and
580
+ prefix before it has a least width, so at 80 columns hpcp's copy bar shows no count (all three as in 1.67).
581
+
582
+ ## Upgrading to 1.67 from 1.66
583
+
584
+ - Nothing needs doing. `mcmd` is unchanged.
585
+ - Fix, library: `format_bytes()` counts a size string in whole bytes: `'4.1G'` is 4100000000 (1.66: 4099999999, from a
586
+ float). hpcp's size options (`-L`, `-F`, `-dis`, `-ddr`) take these values with 1.67.
587
+ - Fix, library: `format_bytes()` shows a size of 1000 Y or more in Y, as `'1000.00 Y'` or `'1024.00 Yi'` (1.66: `KeyError`),
588
+ and `float('inf')` as `'inf Yi'` (1.66: it never returned).
589
+ - Packaging: built with setuptools 77 or later, the metadata names the license as `License-Expression: GPL-3.0-or-later`.
590
+
536
591
  ## Upgrading to 1.66 from 1.65
537
592
 
538
593
  - Nothing needs doing for `mcmd`, which is unchanged, nor for hpcp 9.92, which checks its sizes itself. hpcp up to 9.91
@@ -821,4 +876,4 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
821
876
  ## License
822
877
 
823
878
  GPLv3+ — see the package metadata. Authored by Yufei Pan (<pan@zopyr.us>).
824
- ```
879
+ ```
@@ -37,4 +37,5 @@ tests/test_run_commands.py
37
37
  tests/test_sudo.py
38
38
  tests/test_supervision.py
39
39
  tests/test_task.py
40
+ tests/test_terminal_width.py
40
41
  tests/test_windows.py
@@ -29,9 +29,9 @@ import traceback
29
29
  from pprint import pformat
30
30
 
31
31
  #%% global vars
32
- version = '1.66'
32
+ version = '1.68'
33
33
  __version__ = version
34
- COMMIT_DATE = '2026-11-14'
34
+ COMMIT_DATE = '2026-11-16'
35
35
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
36
36
  # lock for it: each update is one set operation and each snapshot one set.copy(), as for _live_procs below
37
37
  __running_threads = set()
@@ -3347,9 +3347,17 @@ def input_with_timeout_and_countdown(timeout, prompt='Please enter your selectio
3347
3347
  if ended:
3348
3348
  time.sleep(max(deadline - (seconds - 1) - time.monotonic(), 0))
3349
3349
 
3350
+ def _char_width(ch):
3351
+ '''The terminal columns a character takes ( internal ): an East Asian wide character two, a combining mark none'''
3352
+ if ch < "\u0300": # ASCII and Latin-1
3353
+ return 1
3354
+ import unicodedata
3355
+ if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Cf") or "\u1160" <= ch <= "\u11ff":
3356
+ return 0
3357
+ return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
3358
+
3350
3359
  def pretty_format_table(data, delimiter=None, header=None, full=False, remove_empty_columns=False):
3351
3360
  import re
3352
- import unicodedata
3353
3361
  version = 1.21
3354
3362
  _ = version
3355
3363
  if not data:
@@ -3383,12 +3391,7 @@ def pretty_format_table(data, delimiter=None, header=None, full=False, remove_em
3383
3391
  # Widths count terminal columns: an East Asian wide character takes two,
3384
3392
  # a combining mark and an ANSI color code none.
3385
3393
  ansi = re.compile(r"(\x1b\[[0-?]*[ -/]*[@-~])")
3386
- def char_width(ch):
3387
- if ch < "\u0300": # ASCII and Latin-1
3388
- return 1
3389
- if unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Cf") or "\u1160" <= ch <= "\u11ff":
3390
- return 0
3391
- return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
3394
+ char_width = _char_width
3392
3395
  def visible_len(s):
3393
3396
  if "\x1b" in s:
3394
3397
  s = ansi.sub("", s)
@@ -3533,7 +3536,11 @@ def slugify(value, allow_unicode=False):
3533
3536
 
3534
3537
  def get_terminal_size():
3535
3538
  '''
3536
- Get the terminal size
3539
+ Get the terminal size: stdout's terminal, else stdin's (cmd | less), else COLUMNS / LINES, else 240x50 (no terminal).
3540
+
3541
+ A terminal that reports 0 columns or rows does not know its size (a pty nobody set one on: script
3542
+ without a terminal of its own, some CI runners). What it does not know comes from
3543
+ COLUMNS / LINES, else 80x24, what other programs take such a terminal for.
3537
3544
 
3538
3545
  @params:
3539
3546
  None
@@ -3541,9 +3548,11 @@ def get_terminal_size():
3541
3548
  @returns:
3542
3549
  (int,int): the number of columns and rows of the terminal
3543
3550
  '''
3551
+ # ( shutil.get_terminal_size is not enough: before Python 3.11 it returns a terminal's zeros, it does not read stdin's size,
3552
+ # and COLUMNS overrides a real size )
3553
+ answered = True # a terminal answered, maybe with zeros: it is taken for a screen of 80x24 ( so is the log that script writes )
3544
3554
  try:
3545
- import os
3546
- _tsize = os.get_terminal_size()
3555
+ columns, rows = os.get_terminal_size()
3547
3556
  except Exception:
3548
3557
  try:
3549
3558
  import fcntl
@@ -3551,19 +3560,59 @@ def get_terminal_size():
3551
3560
  import termios
3552
3561
  packed = fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))
3553
3562
  rows, columns = struct.unpack('HHHH', packed)[:2]
3554
- _tsize = (columns, rows)
3555
3563
  except Exception:
3556
- import shutil
3557
- _tsize = shutil.get_terminal_size(fallback=(240, 50))
3558
- return _tsize
3564
+ columns = rows = 0
3565
+ answered = False
3566
+ def from_environment(name, fallback):
3567
+ try:
3568
+ value = int(os.environ.get(name, ''))
3569
+ except ValueError:
3570
+ return fallback
3571
+ return value if value > 0 else fallback
3572
+ # 80x24 is what terminfo, curses, ls and shutil take a terminal for when it does not say, so a line that fits never wraps on
3573
+ # its screen; no terminal at all is a log or a pipe, where a wide line costs nothing
3574
+ if columns <= 0:
3575
+ columns = from_environment('COLUMNS', 80 if answered else 240)
3576
+ if rows <= 0:
3577
+ rows = from_environment('LINES', 24 if answered else 50)
3578
+ return os.terminal_size((columns, rows))
3559
3579
 
3560
3580
  # the bar's blocks, and what a stdout whose encoding has no such characters gets for them ( see _writable )
3561
3581
  _BAR_BLOCKS = '▁▂▃▄▅▆▇█'
3562
3582
  _ASCII_BAR = str.maketrans(_BAR_BLOCKS, '.:-=+*%#')
3563
3583
 
3584
+ def _cells(text):
3585
+ '''The terminal columns text takes ( internal ): a wide character two, a combining mark none'''
3586
+ # ASCII and Latin-1, the usual text, is a column a character ( as pretty_format_table's visible_len ): a frame is measured twice
3587
+ # a time it is drawn, twice a second
3588
+ if not text or max(text) < "\u0300":
3589
+ return len(text)
3590
+ return sum(map(_char_width, text))
3591
+
3592
+ def _fit(text, width, from_start=False):
3593
+ '''
3594
+ text cut to width terminal columns ( internal ): its end, back to the last blank that fits and follows neither a digit
3595
+ nor a colon, so a number keeps its label and its unit ( format_bytes writes '1.23 K' ); from_start, its start, at the
3596
+ column
3597
+ '''
3598
+ used = 0
3599
+ for i in (range(len(text) - 1, -1, -1) if from_start else range(len(text))):
3600
+ used += _char_width(text[i])
3601
+ if used > width:
3602
+ if from_start:
3603
+ return text[i + 1:]
3604
+ # a blank after a digit may sit between a number and its unit ( '1.23 K' ), one after a colon between a label and
3605
+ # its number: neither is a place to cut
3606
+ blank = i
3607
+ while blank > 0 and (text[blank] != ' ' or text[blank - 1].isdigit() or text[blank - 1] == ':'):
3608
+ blank -= 1
3609
+ return text[:blank] if blank > 0 else text[:i]
3610
+ return text
3611
+
3564
3612
  def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3565
3613
  '''
3566
- Generate a progress bar string
3614
+ Generate a progress bar string: one line, within one column less than columns ( a line that reaches the last column
3615
+ wraps on some terminals, and a frame that wraps scrolls a row each time it is drawn ), counted in terminal columns
3567
3616
 
3568
3617
  @params:
3569
3618
  iteration - Required : current iteration (Int)
@@ -3579,22 +3628,29 @@ def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3579
3628
  noSuffix = False
3580
3629
  noPercent = False
3581
3630
  noBar = False
3582
- # if total is 0, we don't want to divide by 0
3631
+ width = columns - 1
3632
+ # if total is 0, we don't want to divide by 0: the iteration, padded to clear the last frame. What does not fit gives way
3633
+ # from the prefix's start ( hpcp's is the end of a path ), then from the end
3583
3634
  if total == 0:
3584
- return f'{prefix} iteration:{iteration} {suffix}'.ljust(columns)
3635
+ rest = f' iteration:{iteration} {suffix}'
3636
+ line = _fit(_fit(prefix, width - _cells(rest), from_start=True) + rest, width)
3637
+ return line + ' ' * (width - _cells(line))
3585
3638
  percent = f'|{("{0:.1f}").format(100 * (iteration / float(total)))}% '
3586
- length = columns - len(prefix) - len(suffix) - len(percent) - 3
3639
+ prefix_cells, suffix_cells = _cells(prefix), _cells(suffix)
3640
+ # a bar is length + 1 wide, full or not ( see below ), so a frame is at most columns - 2 wide
3641
+ length = columns - prefix_cells - suffix_cells - len(percent) - 3
3587
3642
  if length <= 0:
3588
- length = columns - len(prefix) - len(suffix) - 3
3643
+ length = columns - prefix_cells - suffix_cells - 3
3589
3644
  noPercent = True
3590
3645
  if length <= 0:
3591
- length = columns - len(suffix) - 3
3646
+ length = columns - suffix_cells - 3
3592
3647
  noPrefix = True
3593
3648
  if length <= 0:
3594
3649
  length = columns - 3
3595
3650
  noSuffix = True
3596
3651
  if length <= 0:
3597
- return f'{prefix}\niteration:\n {iteration}\ntotal:\n {total}\n| {suffix}\n'
3652
+ # 3 columns or fewer: no room for a bar
3653
+ return ''
3598
3654
  if iteration == 0:
3599
3655
  noBar = True
3600
3656
  filled_length = int(length * iteration // total)
@@ -3602,8 +3658,10 @@ def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3602
3658
  fractional_progress = (length * iteration / total) - filled_length
3603
3659
  char_index = int(fractional_progress * (len(progress_chars) - 1))
3604
3660
  bar_char = progress_chars[char_index]
3605
- if filled_length == length:
3606
- bar = progress_chars[-1] * length
3661
+ # past the total too ( a total that was an estimate ): a full bar, not a longer one, and as wide as the bars before it: the
3662
+ # frame is drawn over the one before it, and what it does not cover stays on the screen ( '| 00:00:001' for '| 00:00:00' )
3663
+ if filled_length >= length:
3664
+ bar = progress_chars[-1] * (length + 1)
3607
3665
  else:
3608
3666
  bar = progress_chars[-1] * filled_length + bar_char + '_' * (length - filled_length)
3609
3667
  lineOut = ''
@@ -3661,6 +3719,10 @@ def print_progress_bar(iteration, total, prefix='', suffix=''):
3661
3719
  # the lock held ( docs/limitations.md ) would hang every later frame; it never took the lock before.
3662
3720
  try:
3663
3721
  columns, _ = get_terminal_size()
3722
+ # measured as stdout will write them: a stdout whose errors handler raises ( the default ) writes a character it cannot
3723
+ # write as one '?', whatever its width ( a combining mark takes none, a wide character two ), and a frame measured before
3724
+ # that wraps or leaves the one before it showing
3725
+ prefix, suffix = _writable(prefix, sys.stdout), _writable(suffix, sys.stdout)
3664
3726
  _display._write(_writable(f'\r{_genrate_progress_bar(iteration, total, prefix, suffix, columns)}', sys.stdout))
3665
3727
  if iteration == total and total > 0:
3666
3728
  _display._write('\n')
@@ -3690,7 +3752,6 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3690
3752
  }
3691
3753
  if match:
3692
3754
  number, _, unit = match.groups()
3693
- number = float(number)
3694
3755
  unit = unit.lower().rstrip("b")
3695
3756
  if unit.endswith("i"):
3696
3757
  use_1024_bytes = True
@@ -3707,14 +3768,12 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3707
3768
  power = 2**10
3708
3769
  else:
3709
3770
  power = 10**3
3771
+ # in whole numbers, not a float: '4.1G' is 4100000000 bytes ( 1.66: 4099999999 ); a part of a byte is cut off, as before
3772
+ whole, _, fraction = number.partition(".")
3773
+ size_in_bytes = int(whole + fraction) * power**unit_labels[unit] // 10**len(fraction)
3710
3774
  if to_str:
3711
- return format_bytes(
3712
- size=int(number * (power**unit_labels[unit])),
3713
- use_1024_bytes=use_1024_bytes,
3714
- to_str=True,
3715
- str_format=str_format,
3716
- )
3717
- return int(number * (power**unit_labels[unit]))
3775
+ return format_bytes(size=size_in_bytes, use_1024_bytes=use_1024_bytes, to_str=True, str_format=str_format)
3776
+ return size_in_bytes
3718
3777
  else:
3719
3778
  try:
3720
3779
  return int(size)
@@ -3741,7 +3800,8 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3741
3800
  7: "Zi",
3742
3801
  8: "Yi",
3743
3802
  }
3744
- while size >= power:
3803
+ # Y is the last unit: a larger size stays in Y ( 1.66 stepped past it to a KeyError, and float('inf') never stopped )
3804
+ while size >= power and n < len(power_labels) - 1:
3745
3805
  size /= power
3746
3806
  n += 1
3747
3807
  return f"{size:{str_format}} {' '}{power_labels[n]}".replace(" ", " ")
@@ -3759,7 +3819,7 @@ def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_form
3759
3819
  7: "Z",
3760
3820
  8: "Y",
3761
3821
  }
3762
- while size >= power:
3822
+ while size >= power and n < len(power_labels) - 1:
3763
3823
  size /= power
3764
3824
  n += 1
3765
3825
  return f"{size:{str_format}} {' '}{power_labels[n]}".replace(" ", " ")
multicmd-1.68/setup.py ADDED
@@ -0,0 +1,41 @@
1
+ import setuptools
2
+ from setuptools import setup
3
+ from multiCMD import __version__
4
+
5
+ classifiers = [
6
+ 'Programming Language :: Python :: 3',
7
+ 'Operating System :: POSIX :: Linux',
8
+ 'Operating System :: Microsoft :: Windows',
9
+ ]
10
+ # setuptools 77+ (PEP 639) takes an SPDX license expression and warns about license classifiers (an error next to an
11
+ # expression); older ones (the newest for Python 3.8 and earlier, so all a Python 3.6 install has) know only the
12
+ # free-text license and the classifier. Their sdist and wheel take LICENSE by its name (setuptools 56+, wheel 0.32+).
13
+ if int(setuptools.__version__.split('.')[0]) >= 77:
14
+ license_metadata = {'license_expression': 'GPL-3.0-or-later', 'license_files': ['LICENSE']}
15
+ else:
16
+ license_metadata = {'license': 'GPL-3.0-or-later'}
17
+ classifiers.append('License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)')
18
+
19
+ setup(
20
+ name='multiCMD',
21
+ version=__version__,
22
+ description='Run commands simultaneously',
23
+ long_description=open('README.md', encoding='utf-8').read(),
24
+ long_description_content_type='text/markdown',
25
+ author='Yufei Pan',
26
+ author_email='pan@zopyr.us',
27
+ url='https://github.com/yufei-pan/multiCMD',
28
+ py_modules=['multiCMD'],
29
+ # The mixed-case command is a script file and not an entry point: pip 9 (stock on EL7 and EL8) reads entry_points.txt with a
30
+ # parser that folds case, so two commands that differ only in case make it fail to upgrade or uninstall the package.
31
+ scripts=['scripts/multiCMD'],
32
+ entry_points={
33
+ 'console_scripts': [
34
+ 'mcmd=multiCMD:main',
35
+ 'multicmd=multiCMD:main',
36
+ ],
37
+ },
38
+ classifiers=classifiers,
39
+ python_requires='>=3.6',
40
+ **license_metadata
41
+ )
@@ -110,6 +110,52 @@ def test_format_bytes_reads_every_unit_it_knows(capsys, size, kwargs, expected):
110
110
  assert capsys.readouterr() == ("", "")
111
111
 
112
112
 
113
+ # 1.67: a size is counted in whole numbers, and a part of a byte cut off ( 1.66 multiplied a float: '4.1G' was 4099999999 )
114
+ @pytest.mark.parametrize("size, expected", [
115
+ ("4.1G", 4100000000), ("2.01 K", 2010), ("32.3K", 32300), ("4.1 TB", 4100000000000), ("4.1P", 4100000000000000),
116
+ ("0.1 GiB", 107374182), ("1.5 KiB", 1536), ("12345678901234567891", 12345678901234567891), ("999 Y", 999 * 10 ** 24)], ids=str)
117
+ def test_format_bytes_counts_a_size_in_whole_bytes(size, expected):
118
+ got = format_bytes(size, to_int=True)
119
+ assert got == expected and isinstance(got, int)
120
+
121
+
122
+ def test_format_bytes_counts_every_size_of_two_decimals_exactly():
123
+ # ( 1.66 gave one byte less for 601 of these 50,000 )
124
+ wrong = []
125
+ for unit, power in (("K", 1000), ("G", 1000 ** 3), ("T", 1000 ** 4), ("Ki", 1024), ("Gi", 1024 ** 3)):
126
+ for hundredths in range(10000):
127
+ size = "%d.%02d%s" % (hundredths // 100, hundredths % 100, unit)
128
+ if format_bytes(size, to_int=True) != hundredths * power // 100:
129
+ wrong.append(size)
130
+ assert not wrong, (len(wrong), wrong[:10])
131
+
132
+
133
+ # 1.67: Y is the last unit, and a larger size stays in it ( 1.66 raised KeyError: 9 from 1000 Y, or 1024 Yi, up )
134
+ @pytest.mark.parametrize("size, kwargs, expected", [
135
+ (999 * 10 ** 24, {"use_1024_bytes": False}, "999.00 Y"), (10 ** 27, {"use_1024_bytes": False}, "1000.00 Y"),
136
+ (1023 * 2 ** 80, {}, "1023.00 Yi"), (2 ** 90, {}, "1024.00 Yi"), (2 ** 90, {"use_1024_bytes": True, "to_str": True}, "1024.00 Yi"),
137
+ ("1000 Y", {"to_str": True}, "1000.00 Y"), ("1024 Yi", {"to_str": True}, "1024.00 Yi")], ids=str)
138
+ def test_format_bytes_at_the_end_of_the_last_unit(size, kwargs, expected):
139
+ assert format_bytes(size, **kwargs) == expected
140
+
141
+
142
+ @pytest.mark.parametrize("size, kwargs, unit, number", [
143
+ (10 ** 40, {"use_1024_bytes": False}, "Y", 1e16), (1e30, {"use_1024_bytes": False}, "Y", 1e6), (2 ** 200, {}, "Yi", 2.0 ** 120),
144
+ ("5000000 YB", {"to_str": True}, "Y", 5e6), ("1048576 YiB", {"to_str": True}, "Yi", 2.0 ** 20)], ids=str)
145
+ def test_format_bytes_shows_a_size_far_past_the_last_unit_in_it(size, kwargs, unit, number):
146
+ # ( eight divisions in floats: 10 ** 40 shows as 9999999999999998.00 Y )
147
+ got_number, got_unit = format_bytes(size, **kwargs).split(" ")
148
+ assert got_unit == unit and float(got_number) == pytest.approx(number)
149
+
150
+
151
+ def test_format_bytes_shows_an_endless_size_in_the_last_unit():
152
+ # ( 1.66's unit loop never ended: inf divided by 1024 is inf; in a child, so a loop that does not end fails, not hangs )
153
+ shown = subprocess.run([sys.executable, "-c", "import multiCMD; print(multiCMD.format_bytes(float('inf')))"],
154
+ cwd=str(Path(multiCMD.__file__).resolve().parent), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
155
+ universal_newlines=True, timeout=60)
156
+ assert (shown.returncode, shown.stdout, shown.stderr) == (0, "inf Yi\n", "")
157
+
158
+
113
159
  def test_int_to_color_deterministic_and_in_range():
114
160
  assert int_to_color(0x123456) == (36, 103, 171)
115
161
  assert int_to_color(0) == (160, 160, 160)
@@ -148,7 +194,7 @@ def test_progress_bar_on_a_stdout_that_cannot_write_its_blocks(monkeypatch):
148
194
  out.flush()
149
195
  assert out.buffer.getvalue().decode('ascii') == (
150
196
  "\rProgress: |" + "#" * 24 + "=" + "_" * 25 + "|50.0% | Complete"
151
- "\rProgress: |" + "#" * 48 + "|100.0% | Complete\n"
197
+ "\rProgress: |" + "#" * 49 + "|100.0% | Complete\n"
152
198
  )
153
199
 
154
200
 
@@ -157,7 +203,22 @@ def test_progress_bar_with_a_name_its_stdout_cannot_write(monkeypatch):
157
203
  out = ascii_stdout(monkeypatch, 'utf-8', 'strict')
158
204
  print_progress_bar(3, 0, prefix='dir/caf\udce9', suffix='s')
159
205
  out.flush()
160
- assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(80)
206
+ assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(79)
207
+
208
+
209
+ def test_progress_bar_is_measured_as_its_stdout_writes_it(monkeypatch):
210
+ # an ASCII stdout ( Python 3.6 in a C locale ) writes a combining mark, which takes no column, as a '?' that takes one, and a wide
211
+ # character, which takes two, as one: a frame measured before that wrapped ( 80 columns and more ) or came out short, leaving the
212
+ # end of the frame before it showing
213
+ out = ascii_stdout(monkeypatch, 'ascii', 'strict')
214
+ print_progress_bar(7, 0, prefix='e\u0301' * 60, suffix='s')
215
+ print_progress_bar(7, 0, prefix='\u4e2d' * 30, suffix='s')
216
+ print_progress_bar(5, 10, prefix='e\u0301' * 12, suffix='\u4e2d' * 3)
217
+ print_progress_bar(5, 10, prefix='dir', suffix='s')
218
+ out.flush()
219
+ frames = out.buffer.getvalue().decode('ascii').split('\r')[1:]
220
+ assert [len(frame) for frame in frames] == [79, 79, 78, 78]
221
+ assert frames[0].endswith('e? | iteration:7 | s') and frames[2].startswith('e?' * 12 + ' |') and frames[2].endswith('|50.0% | ???')
161
222
 
162
223
 
163
224
  def test_progress_bar_in_a_c_locale_python():
@@ -188,14 +249,14 @@ def test_get_terminal_size_reads_columns_from_stdin_when_stdout_is_piped():
188
249
  try:
189
250
  fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 200, 0, 0))
190
251
  out = subprocess.run(
191
- [sys.executable, "-c", "import multiCMD; print(*multiCMD.get_terminal_size()[:2])"],
252
+ [sys.executable, "-c", "import os, multiCMD; size = multiCMD.get_terminal_size(); print(*size[:2], isinstance(size, os.terminal_size))"],
192
253
  stdin=slave, stdout=subprocess.PIPE, cwd=str(Path(__file__).resolve().parents[1]),
193
254
  universal_newlines=True, check=True,
194
255
  ).stdout
195
256
  finally:
196
257
  os.close(slave)
197
258
  os.close(master)
198
- assert out.split() == ["200", "40"]
259
+ assert out.split() == ["200", "40", "True"]
199
260
 
200
261
 
201
262
  @pytest.fixture
@@ -0,0 +1,377 @@
1
+ '''A progress line fits its terminal (1.68): a terminal of no size counts as unknown, and a frame is cut to one column less
2
+ than the width, in terminal columns.'''
3
+ import os
4
+ import re
5
+ import select
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ import unicodedata
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ import multiCMD
15
+ from multiCMD import _genrate_progress_bar, get_terminal_size, print_progress_bar
16
+
17
+ ROOT = str(Path(__file__).resolve().parents[1])
18
+ posix_only = pytest.mark.skipif(os.name != 'posix', reason='needs a pseudo-terminal')
19
+
20
+ # hpcp's removal and listing lines ( hpcp 9.95: prefix=path[-50:], the suffix after it, its numbers from format_bytes(), which
21
+ # writes a blank between a number and its unit: '1.23 K', '1.15 Gi', and '45.00 ' with none )
22
+ PATH = '/srv/data/projects/2026/run-0042/outputs/checkpoints/step-001200/model.safetensors'
23
+
24
+
25
+ def fb(count):
26
+ return multiCMD.format_bytes(count, use_1024_bytes=False, to_str=True)
27
+
28
+
29
+ REMOVAL = f'Removed: {fb(1230)} Folders: {fb(45)} | Overall: {fb(1230000)} Files'
30
+ LISTING = f'Files: {fb(1230)} Links: {fb(12)} Folders: {fb(45)} Size: {multiCMD.format_bytes(1.15 * 2 ** 30)}B | Overall: {fb(1230000)} Files'
31
+ WIDE_PATH = '/数据/项目/二〇二六/运行记录/输出结果/检查点/第一千二百步/模型权重文件.safetensors'
32
+
33
+
34
+ def cells(text):
35
+ '''The terminal columns text takes, by the test's own count: a wide character two, a combining mark none.'''
36
+ return sum(0 if unicodedata.combining(ch) else 2 if unicodedata.east_asian_width(ch) in ('W', 'F') else 1 for ch in text)
37
+
38
+
39
+ def frames(text):
40
+ '''The frames in what print_progress_bar wrote: each starts with a carriage return.'''
41
+ return [frame for frame in re.split(r'[\r\n]', text) if frame]
42
+
43
+
44
+ def env_without_a_size():
45
+ env = dict(os.environ)
46
+ env.pop('COLUMNS', None)
47
+ env.pop('LINES', None)
48
+ return env
49
+
50
+
51
+ def at_a_pty(code, rows, columns):
52
+ '''What a child Python running code writes to a pty of rows x columns (its stdin and stdout), up to the "END" it writes last,
53
+ with the pty's \\r\\n made \\n.'''
54
+ import fcntl
55
+ import pty
56
+ import struct
57
+ import termios
58
+ master, slave = pty.openpty()
59
+ try:
60
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, columns, 0, 0))
61
+ child = subprocess.Popen([sys.executable, '-c', code + '\nimport sys; sys.stdout.write("END"); sys.stdout.flush()'],
62
+ stdin=slave, stdout=slave, stderr=subprocess.PIPE, cwd=ROOT, env=env_without_a_size())
63
+ finally:
64
+ os.close(slave)
65
+ output = b''
66
+ deadline = time.monotonic() + 60
67
+ try:
68
+ while not output.endswith(b'END') and time.monotonic() < deadline:
69
+ if not select.select([master], [], [], 1)[0]:
70
+ continue
71
+ try:
72
+ chunk = os.read(master, 65536)
73
+ except OSError: # Linux: EIO, the child has closed its side
74
+ break
75
+ if not chunk:
76
+ break
77
+ output += chunk
78
+ _, err = child.communicate(timeout=60)
79
+ finally:
80
+ os.close(master)
81
+ assert child.returncode == 0 and err == b'', err
82
+ assert output.endswith(b'END'), output
83
+ return output[:-3].decode('utf-8', 'replace').replace('\r\n', '\n')
84
+
85
+
86
+ def test_the_test_strings_are_what_format_bytes_writes():
87
+ # REMOVAL and LISTING are the suffixes of hpcp 9.95's removal line ( _RemoveProgress.show ) and its listing line, with this
88
+ # module's own format_bytes: hpcp's code is not read. A number and its unit are two words ( the first 1.68 build tested
89
+ # '1.23K' and cut 'Size: 123.45 GiB' after its number )
90
+ assert REMOVAL == 'Removed: 1.23 K Folders: 45.00 | Overall: 1.23 M Files'
91
+ assert LISTING == 'Files: 1.23 K Links: 12.00 Folders: 45.00 Size: 1.15 GiB | Overall: 1.23 M Files'
92
+
93
+
94
+ @pytest.mark.parametrize('reported, environ, expected', [
95
+ # a terminal that does not say: 80x24, what other programs take it for, so a line that fits never wraps on its screen
96
+ ((0, 0), {}, (80, 24)),
97
+ ((0, 0), {'COLUMNS': '100', 'LINES': '40'}, (100, 40)),
98
+ ((0, 40), {}, (80, 40)),
99
+ ((200, 0), {}, (200, 24)),
100
+ ((200, 0), {'LINES': '30'}, (200, 30)),
101
+ ((0, 0), {'COLUMNS': '0', 'LINES': '-3'}, (80, 24)),
102
+ ((0, 0), {'COLUMNS': 'wide', 'LINES': ''}, (80, 24)),
103
+ # a size the terminal knows wins, as before
104
+ ((200, 40), {'COLUMNS': '100', 'LINES': '10'}, (200, 40)),
105
+ ])
106
+ def test_get_terminal_size_takes_a_reported_zero_as_unknown(monkeypatch, reported, environ, expected):
107
+ # a pty nobody set a size on (script without a terminal, a serial console, some CI runners) reports 0x0; 1.67 returned it
108
+ monkeypatch.setattr(os, 'get_terminal_size', lambda *args: os.terminal_size(reported))
109
+ monkeypatch.delenv('COLUMNS', raising=False)
110
+ monkeypatch.delenv('LINES', raising=False)
111
+ for name, value in environ.items():
112
+ monkeypatch.setenv(name, value)
113
+ size = get_terminal_size()
114
+ assert isinstance(size, os.terminal_size) and tuple(size) == expected
115
+
116
+
117
+ @pytest.mark.parametrize('environ, expected', [
118
+ ({}, ['240', '50']),
119
+ ({'COLUMNS': '100', 'LINES': '30'}, ['100', '30']),
120
+ ])
121
+ def test_get_terminal_size_without_a_terminal_is_240x50_or_what_the_environment_says(environ, expected):
122
+ # no terminal at all is a pipe or a log: nothing wraps, so the wide fallback stays ( a terminal that answered 0 is 80x24 )
123
+ code = 'import sys, multiCMD; sys.stderr.write(" ".join(map(str, multiCMD.get_terminal_size()[:2])))'
124
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
125
+ cwd=ROOT, env=dict(env_without_a_size(), **environ), universal_newlines=True, timeout=60)
126
+ assert result.stderr.split() == expected
127
+
128
+
129
+ @posix_only
130
+ @pytest.mark.parametrize('stdout_is_the_pty, size, expected', [
131
+ (True, (0, 0), ['80', '24']),
132
+ # stdout a pipe ( cmd | less ): stdin's terminal answers, with zeros too, so it is a terminal of no size and not no terminal ( 240x50 )
133
+ (False, (0, 0), ['80', '24']),
134
+ (False, (30, 100), ['100', '30']),
135
+ ], ids=['stdout', 'stdin', 'stdin-sized'])
136
+ def test_get_terminal_size_of_a_pty(stdout_is_the_pty, size, expected):
137
+ import fcntl
138
+ import pty
139
+ import struct
140
+ import termios
141
+ master, slave = pty.openpty()
142
+ code = 'import sys, multiCMD; sys.stderr.write(" ".join(map(str, multiCMD.get_terminal_size()[:2])))'
143
+ try:
144
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', size[0], size[1], 0, 0))
145
+ result = subprocess.run([sys.executable, '-c', code], stdin=slave, stdout=slave if stdout_is_the_pty else subprocess.PIPE,
146
+ stderr=subprocess.PIPE, cwd=ROOT, env=env_without_a_size(), universal_newlines=True, timeout=60)
147
+ finally:
148
+ os.close(slave)
149
+ os.close(master)
150
+ assert result.stderr.split() == expected
151
+
152
+
153
+ @posix_only
154
+ def test_a_pty_command_gets_a_window_of_80x24_less_the_prefix_at_a_terminal_of_no_size():
155
+ # 1.67 gave the command a window of 20 columns by 0 rows ( the terminal's zeros ), a pager or a table in it no room
156
+ code = ('import fcntl, struct, termios, multiCMD\n'
157
+ 'master, slave = multiCMD._open_pty(4)\n'
158
+ 'rows, columns = struct.unpack("HHHH", fcntl.ioctl(slave, termios.TIOCGWINSZ, b"\\0" * 8))[:2]\n'
159
+ 'print(rows, columns)')
160
+ assert at_a_pty(code, 0, 0).split() == ['24', '76']
161
+
162
+
163
+ @posix_only
164
+ def test_a_table_gets_80_columns_at_a_terminal_of_no_size():
165
+ # 1.67 cut every column to its heading's width ( 'a |xxx..', 10 columns a row ): the zero was the width
166
+ code = ('import sys, multiCMD\n'
167
+ 'sys.stdout.write(multiCMD.pretty_format_table([["name", "value"], ["a", "x" * 100], ["b", "y" * 30]]))')
168
+ lines = at_a_pty(code, 0, 0).split('\n')
169
+ assert [len(line) for line in lines[:4]] == [80] * 4 and lines[2].startswith('a |xxx') and lines[2].endswith('xxx..'), lines
170
+ assert lines[3] == 'b |' + 'y' * 30 + ' ' * 45, lines
171
+
172
+
173
+ @posix_only
174
+ def test_a_bar_of_a_known_total_stays_on_one_line_at_a_terminal_of_no_size():
175
+ # 1.67 took the 0 columns for a width, and each frame came out over six lines
176
+ shown = at_a_pty('import multiCMD\nfor i in range(11): multiCMD.print_progress_bar(i, 10, "p", "s")', 0, 0)
177
+ assert shown.count('\n') == 1 and shown.endswith('\n'), shown
178
+ assert len(frames(shown)) == 11 and all(cells(frame) <= 79 for frame in frames(shown)), shown
179
+ assert frames(shown)[5].startswith('p |') and frames(shown)[5].endswith('|50.0% | s'), shown
180
+
181
+
182
+ @posix_only
183
+ def test_a_short_line_stays_on_one_row_at_a_terminal_of_no_size():
184
+ # a serial console or `qm terminal` gives 0x0 until someone runs resize ( known from the platform, not tested ), with a real
185
+ # 80-column screen behind it: the first 1.68 build padded every frame to 239 columns, three rows that scrolled twice a
186
+ # second ( 1.67 wrote 58 and did not pad )
187
+ shown = at_a_pty('import multiCMD\nfor i in range(3): multiCMD.print_progress_bar(i, 0, "/scratch/old-runs/job-1234", "Removed: 1.23 K")', 0, 0)
188
+ assert '\n' not in shown and len(frames(shown)) == 3, shown
189
+ assert [len(frame) for frame in frames(shown)] == [79] * 3 and frames(shown)[2].rstrip() == (
190
+ '/scratch/old-runs/job-1234 | iteration:2 | Removed: 1.23 K'), shown
191
+
192
+
193
+ @posix_only
194
+ def test_a_long_prefix_does_not_wrap_at_80_columns():
195
+ # hpcp's removal and listing lines pass 80 columns with a path of 50 ( this test's: 122 and 149 ): 1.67 wrapped them, and
196
+ # each frame scrolled a row. %a, not %r: the child's code stays ASCII, so it starts under a C locale ( Python 3.6 ) too
197
+ code = ('import multiCMD\n'
198
+ 'for i in range(3):\n'
199
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
200
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
201
+ ' multiCMD.print_progress_bar(i, 0, %a, %a)\n'
202
+ % (PATH[-50:], REMOVAL, PATH[-50:], LISTING, WIDE_PATH[-50:], REMOVAL))
203
+ shown = at_a_pty(code, 24, 80)
204
+ assert '\n' not in shown, shown
205
+ assert len(frames(shown)) == 9 and all(cells(frame) <= 79 for frame in frames(shown)), shown
206
+ removal, listing, wide = frames(shown)[-3:]
207
+ # the prefix gives way first, from its start: the end of the path stays, and the counts stay whole
208
+ assert removal.rstrip() == 'tensors | iteration:2 | ' + REMOVAL, removal
209
+ assert wide.rstrip() == 'tensors | iteration:2 | ' + REMOVAL, wide
210
+ # wider than the terminal without the path: the end gives way a whole field at a time ( 1.15 GiB stays whole, then the
211
+ # label of a number that does not fit goes with it )
212
+ assert listing.rstrip() == ' iteration:2 | Files: 1.23 K Links: 12.00 Folders: 45.00 Size: 1.15 GiB |', listing
213
+
214
+
215
+ def test_a_frame_is_measured_as_an_ascii_stdout_writes_it():
216
+ # a combining mark counts none, and an ASCII stdout ( PYTHONIOENCODING, or Python 3.6 in a C locale ) writes it as one '?': a
217
+ # decomposed name ( macOS writes them ), measured before it is written, came out 109 columns at 80, and wrapped. Only a
218
+ # combining mark shows it: a wide character is two columns and written as one '?', so the frame comes out narrower
219
+ prefix = 'e\u0301' * 30
220
+ code = ('import multiCMD\n'
221
+ 'for i in range(3): multiCMD.print_progress_bar(i, 0, %a, "| Removed: 1.23 K")\n' % prefix)
222
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
223
+ cwd=ROOT, env=dict(env_without_a_size(), PYTHONIOENCODING='ascii', COLUMNS='80'), timeout=60)
224
+ assert result.returncode == 0 and result.stderr == b'', result.stderr
225
+ shown = frames(result.stdout.decode('ascii'))
226
+ # the prefix as the stream writes it is 62 columns, and what is left of the 79 after the rest of the line is its end
227
+ written, rests = 'e?' * 30 + ' |', [' iteration:%d | Removed: 1.23 K' % i for i in range(3)]
228
+ assert shown == [written[len(rest) - 79:] + rest for rest in rests], shown
229
+
230
+
231
+ def test_a_pipe_draws_its_frames_at_240_columns():
232
+ # no terminal, and no COLUMNS ( the environment has none ): 240 columns, as in 1.67
233
+ code = ('import multiCMD\n'
234
+ 'multiCMD.print_progress_bar(5, 10, "p", "s")\n'
235
+ 'multiCMD.print_progress_bar(10, 10, "p", "s")\n'
236
+ 'multiCMD.print_progress_bar(3, 0, "p", "s")\n')
237
+ result = subprocess.run([sys.executable, '-c', code], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
238
+ cwd=ROOT, env=dict(env_without_a_size(), PYTHONIOENCODING='utf-8'), timeout=60)
239
+ assert result.returncode == 0 and result.stderr == b'', result.stderr
240
+ full = '\N{FULL BLOCK}'
241
+ assert result.stdout.decode('utf-8') == (
242
+ '\rp |' + full * 112 + '\N{LOWER ONE EIGHTH BLOCK}' + '_' * 112 + '|50.0% | s'
243
+ '\rp |' + full * 224 + '|100.0% | s\n'
244
+ # padded to clear the last frame, to 239 columns ( 1.67: 240 )
245
+ '\r' + 'p | iteration:3 | s'.ljust(239))
246
+
247
+
248
+ @pytest.mark.parametrize('columns, shown', [
249
+ (240, '/outputs/checkpoints/step-001200/model.safetensors | iteration:7 | ' + REMOVAL),
250
+ (80, 'tensors | iteration:7 | ' + REMOVAL),
251
+ (73, ' | iteration:7 | ' + REMOVAL),
252
+ (71, ' iteration:7 | ' + REMOVAL),
253
+ # the end gives way a word at a time: ' Files', the word after a number's unit, goes on its own; the number keeps its unit
254
+ (70, ' iteration:7 | Removed: 1.23 K Folders: 45.00 | Overall: 1.23 M'),
255
+ # a label goes with its number ( 'Overall: 1.23 M' did not fit; 'Overall:' alone is not left )
256
+ (64, ' iteration:7 | Removed: 1.23 K Folders: 45.00 |'),
257
+ # 'Folders:' fits in the 39 columns, its number does not
258
+ (40, ' iteration:7 | Removed: 1.23 K'),
259
+ # '1.23' fits in the 29 columns, its unit does not
260
+ (30, ' iteration:7 |'),
261
+ # a field that fits to the last column stays ( the blank after it is the first thing that does not fit )
262
+ (31, ' iteration:7 | Removed: 1.23 K'),
263
+ (8, ' iterat'),
264
+ (1, ''),
265
+ ])
266
+ def test_a_frame_of_no_total_gives_way_from_the_prefix_then_the_end(columns, shown):
267
+ frame = _genrate_progress_bar(7, 0, PATH[-50:] + ' |', '| ' + REMOVAL, columns)
268
+ assert frame == shown.ljust(columns - 1)
269
+
270
+
271
+ def test_a_number_is_not_cut_from_its_unit_at_80_columns():
272
+ # hpcp's listing at 80 columns, five minutes in: 1.68's first build cut it at the blank before the unit, 'Size: 123.45' of 123.45 GiB
273
+ suffix = '| Files: 123.45 K Links: 1.20 K Folders: 12.34 K Size: 123.45 GiB '
274
+ frame = _genrate_progress_bar(300, 0, PATH[-50:] + ' |', suffix, 80)
275
+ assert frame == ' iteration:300 | Files: 123.45 K Links: 1.20 K Folders: 12.34 K'.ljust(79)
276
+
277
+
278
+ def a_broken_end(kept, whole):
279
+ '''Why a frame of the line whole ends badly, at kept ( what is left of whole from ' iteration:' on ), else None: inside a
280
+ word, on a label without its number, or on a number without its unit. A plain count ( '45.00' ) is complete: the word after
281
+ it is a label or a bar, not a unit.'''
282
+ if not whole.startswith(kept):
283
+ return 'is not the start of the line'
284
+ if kept != whole.rstrip() and whole[len(kept)] != ' ':
285
+ return 'ends inside a word'
286
+ if kept.endswith(':'):
287
+ return 'ends on a label without its number'
288
+ after = whole[len(kept):].split()
289
+ if re.fullmatch(r'\d+(\.\d+)?', kept.split(' ')[-1]) and after and after[0][:1].isalpha() and not after[0].endswith(':'):
290
+ return 'ends on a number without its unit'
291
+ return None
292
+
293
+
294
+ @pytest.mark.parametrize('prefix', [PATH[-50:], WIDE_PATH[-50:]], ids=['path', 'wide-path'])
295
+ @pytest.mark.parametrize('suffix', [REMOVAL, LISTING, 'Files: 123.45 K Links: 1.20 K Folders: 12.34 K Size: 123.45 GiB '],
296
+ ids=['removal', 'listing', 'large-counts'])
297
+ def test_a_frame_never_ends_inside_a_field_at_any_width(prefix, suffix):
298
+ # hpcp's lines at 20 to 200 columns: the end gives way a field at a time, after what is left of the prefix. 61cedd0 cut at
299
+ # any blank, and ended on a label without its number ( 'Removed:' ) and on a number without its unit
300
+ suffix = '| ' + suffix
301
+ whole = ' iteration:7 ' + suffix
302
+ for columns in range(20, 201):
303
+ frame = _genrate_progress_bar(7, 0, prefix + ' |', suffix, columns)
304
+ shown = frame.rstrip()
305
+ kept = shown[shown.index(' iteration:'):]
306
+ assert cells(frame) == columns - 1 and a_broken_end(kept, whole) is None, (columns, a_broken_end(kept, whole), shown)
307
+
308
+
309
+ @pytest.mark.parametrize('text, expected', [
310
+ ('', 0), ('abc', 3), ('caf\u00e9', 4), ('\u00ff\u0100\u02ff', 3),
311
+ # U+0300 is where the count by length stops: a combining mark takes none, a format character ( zero width space ) none, a Hangul
312
+ # vowel jamo none, a wide character ( Chinese, full-width ) two, an emoji two
313
+ ('\u0300', 0), ('e\u0301', 1), ('a\u200bb', 2), ('\u1160', 0), ('\u4e2d\u6587', 4), ('ab\u4e2d', 4), ('\uff21', 2), ('\U0001f600x', 3),
314
+ ('x' * 300 + '\u4e2d', 302),
315
+ ])
316
+ def test_cells_counts_a_character_by_its_unicode_width(text, expected):
317
+ # the module's own count, by Unicode's width of each character: no terminal measures it ( a tab or a newline counts one:
318
+ # docs/limitations.md, deferred to 1.69 ). ASCII and Latin-1, the usual text, is counted by length: a fast path that must give
319
+ # what the count by character gives
320
+ assert multiCMD._cells(text) == expected
321
+
322
+
323
+ def test_a_frame_counts_a_wide_character_as_two_columns_and_a_combining_mark_as_none():
324
+ frame = _genrate_progress_bar(7, 0, WIDE_PATH[-50:] + ' |', '| ' + REMOVAL, 109)
325
+ # ( padded with a blank where a wide character did not fit in the last column )
326
+ assert cells(frame) == 108 and frame.startswith('一千二百步/') and frame.endswith(REMOVAL + ' '), frame
327
+ assert _genrate_progress_bar(7, 0, WIDE_PATH[-50:] + ' |', '| ' + REMOVAL, 110).startswith('第一千二百步/'), frame
328
+ # the suffix's wide characters count too: what is left of the prefix is cut to fit them
329
+ rest = ' iteration:7 | 已删除: 1.23 K 文件夹: 45.00 '
330
+ frame = _genrate_progress_bar(7, 0, PATH[-50:] + ' |', '| 已删除: 1.23 K 文件夹: 45.00 ', 80)
331
+ assert cells(frame) == 79 and frame.rstrip() == (PATH[-50:] + ' |')[-(79 - cells(rest)):] + rest.rstrip(), frame
332
+ # with a known total, the bar is what gives way
333
+ frame = _genrate_progress_bar(5, 10, '中文前缀 |', '| 后缀', 40)
334
+ assert cells(frame) == 38 and frame.startswith('中文前缀 |') and frame.endswith('|50.0% | 后缀'), frame
335
+ # a combining mark takes none
336
+ frame = _genrate_progress_bar(7, 0, 'cafe\N{COMBINING ACUTE ACCENT} |', '| s', 40)
337
+ assert cells(frame) == 39 and len(frame) == 40, frame
338
+
339
+
340
+ def test_a_bar_of_a_known_total_at_a_terminal_too_narrow_for_it():
341
+ # 1.67 wrote the frame over six lines at 3 columns or fewer
342
+ assert [_genrate_progress_bar(5, 10, 'p |', '| s', columns) for columns in (1, 2, 3)] == ['', '', '']
343
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 5) == '\N{FULL BLOCK}\N{LOWER ONE EIGHTH BLOCK}_'
344
+
345
+
346
+ def test_a_bar_of_a_known_total_drops_its_percent_before_it_shrinks():
347
+ # 15 columns: no room for the percent, so the bar takes its place and the prefix and suffix stay
348
+ assert _genrate_progress_bar(5, 10, 'p |', '| s', 15) == 'p |' + '\N{FULL BLOCK}' * 3 + '\N{LOWER ONE EIGHTH BLOCK}' + '_' * 3 + '| s'
349
+
350
+
351
+ def test_a_bar_of_a_known_total_drops_a_long_prefix_and_its_percent():
352
+ # 20 columns: the prefix, which the bar of a known total drops whole ( the no-total frame cuts it from its start ), and the percent
353
+ assert _genrate_progress_bar(5, 10, 'x' * 30 + ' |', '| s', 20) == '\N{FULL BLOCK}' * 7 + '\N{LOWER ONE EIGHTH BLOCK}' + '_' * 7 + '| s'
354
+
355
+
356
+ def test_a_bar_past_its_total_is_full_not_longer():
357
+ # a total that was an estimate: 1.67 drew a bar one and a half times its length, over the terminal's width
358
+ frame = _genrate_progress_bar(15, 10, 'p |', '| s', 40)
359
+ assert frame == 'p |' + '\N{FULL BLOCK}' * 24 + '|150.0% | s' and cells(frame) == 38
360
+
361
+
362
+ @pytest.mark.parametrize('columns', [40, 80, 240])
363
+ def test_the_last_frame_of_a_bar_covers_the_one_before_it(columns):
364
+ # a frame is drawn over the one before it from the line's start, and what it does not cover stays: 1.67's full bar was one
365
+ # column shorter than the others, and a bar of 10 ended '| 00:00:001' for '| 00:00:00' ( hpcp's copy bar too )
366
+ drawn = [_genrate_progress_bar(i, 10, '10 files |', '| 3.2 F/s | 00:00:0%d' % (10 - i), columns) for i in range(1, 11)]
367
+ assert [len(frame) for frame in drawn] == [columns - 2] * 10
368
+ line = []
369
+ for frame in drawn:
370
+ line[:len(frame)] = list(frame)
371
+ assert ''.join(line) == drawn[-1] and drawn[-1].endswith('| 3.2 F/s | 00:00:00')
372
+
373
+
374
+ def test_print_progress_bar_draws_at_one_column_less_than_the_terminal(monkeypatch, capsys):
375
+ monkeypatch.setattr(multiCMD, 'get_terminal_size', lambda: os.terminal_size((80, 24)))
376
+ print_progress_bar(7, 0, PATH[-50:], REMOVAL)
377
+ assert capsys.readouterr().out == '\r' + ('tensors | iteration:7 | ' + REMOVAL).ljust(79)
multicmd-1.66/setup.py DELETED
@@ -1,31 +0,0 @@
1
- from setuptools import setup
2
- from multiCMD import __version__
3
-
4
- setup(
5
- name='multiCMD',
6
- version=__version__,
7
- description='Run commands simultaneously',
8
- long_description=open('README.md', encoding='utf-8').read(),
9
- long_description_content_type='text/markdown',
10
- author='Yufei Pan',
11
- author_email='pan@zopyr.us',
12
- url='https://github.com/yufei-pan/multiCMD',
13
- py_modules=['multiCMD'],
14
- # The mixed-case command is a script file and not an entry point: pip 9 (stock on EL7 and EL8) reads entry_points.txt with a
15
- # parser that folds case, so two commands that differ only in case make it fail to upgrade or uninstall the package.
16
- scripts=['scripts/multiCMD'],
17
- entry_points={
18
- 'console_scripts': [
19
- 'mcmd=multiCMD:main',
20
- 'multicmd=multiCMD:main',
21
- ],
22
- },
23
- classifiers=[
24
- 'Programming Language :: Python :: 3',
25
- 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
26
- 'Operating System :: POSIX :: Linux',
27
- 'Operating System :: Microsoft :: Windows',
28
- ],
29
- python_requires='>=3.6',
30
- license='GPLv3+',
31
- )
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes