multiCMD 1.61__tar.gz → 1.62__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 (40) hide show
  1. {multicmd-1.61 → multicmd-1.62}/PKG-INFO +34 -8
  2. {multicmd-1.61 → multicmd-1.62}/README.md +33 -7
  3. {multicmd-1.61 → multicmd-1.62}/multiCMD.egg-info/PKG-INFO +34 -8
  4. {multicmd-1.61 → multicmd-1.62}/multiCMD.py +94 -21
  5. {multicmd-1.61 → multicmd-1.62}/tests/test_cli_closed_stdout.py +276 -0
  6. {multicmd-1.61 → multicmd-1.62}/tests/test_helpers.py +40 -0
  7. {multicmd-1.61 → multicmd-1.62}/LICENSE +0 -0
  8. {multicmd-1.61 → multicmd-1.62}/multiCMD.egg-info/SOURCES.txt +0 -0
  9. {multicmd-1.61 → multicmd-1.62}/multiCMD.egg-info/dependency_links.txt +0 -0
  10. {multicmd-1.61 → multicmd-1.62}/multiCMD.egg-info/entry_points.txt +0 -0
  11. {multicmd-1.61 → multicmd-1.62}/multiCMD.egg-info/top_level.txt +0 -0
  12. {multicmd-1.61 → multicmd-1.62}/scripts/multiCMD +0 -0
  13. {multicmd-1.61 → multicmd-1.62}/setup.cfg +0 -0
  14. {multicmd-1.61 → multicmd-1.62}/setup.py +0 -0
  15. {multicmd-1.61 → multicmd-1.62}/tests/test_api.py +0 -0
  16. {multicmd-1.61 → multicmd-1.62}/tests/test_async_executor.py +0 -0
  17. {multicmd-1.61 → multicmd-1.62}/tests/test_cli.py +0 -0
  18. {multicmd-1.61 → multicmd-1.62}/tests/test_cli_input.py +0 -0
  19. {multicmd-1.61 → multicmd-1.62}/tests/test_cli_summary.py +0 -0
  20. {multicmd-1.61 → multicmd-1.62}/tests/test_display.py +0 -0
  21. {multicmd-1.61 → multicmd-1.62}/tests/test_embed.py +0 -0
  22. {multicmd-1.61 → multicmd-1.62}/tests/test_env.py +0 -0
  23. {multicmd-1.61 → multicmd-1.62}/tests/test_expand_ranges.py +0 -0
  24. {multicmd-1.61 → multicmd-1.62}/tests/test_handover.py +0 -0
  25. {multicmd-1.61 → multicmd-1.62}/tests/test_interrupts.py +0 -0
  26. {multicmd-1.61 → multicmd-1.62}/tests/test_packaging.py +0 -0
  27. {multicmd-1.61 → multicmd-1.62}/tests/test_parsing.py +0 -0
  28. {multicmd-1.61 → multicmd-1.62}/tests/test_pass_fds.py +0 -0
  29. {multicmd-1.61 → multicmd-1.62}/tests/test_ping.py +0 -0
  30. {multicmd-1.61 → multicmd-1.62}/tests/test_pool.py +0 -0
  31. {multicmd-1.61 → multicmd-1.62}/tests/test_process_groups.py +0 -0
  32. {multicmd-1.61 → multicmd-1.62}/tests/test_pty.py +0 -0
  33. {multicmd-1.61 → multicmd-1.62}/tests/test_reader.py +0 -0
  34. {multicmd-1.61 → multicmd-1.62}/tests/test_regressions.py +0 -0
  35. {multicmd-1.61 → multicmd-1.62}/tests/test_run_command.py +0 -0
  36. {multicmd-1.61 → multicmd-1.62}/tests/test_run_commands.py +0 -0
  37. {multicmd-1.61 → multicmd-1.62}/tests/test_sudo.py +0 -0
  38. {multicmd-1.61 → multicmd-1.62}/tests/test_supervision.py +0 -0
  39. {multicmd-1.61 → multicmd-1.62}/tests/test_task.py +0 -0
  40. {multicmd-1.61 → multicmd-1.62}/tests/test_windows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.61
3
+ Version: 1.62
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -119,7 +119,7 @@ exit status:
119
119
  N several commands: how many failed, capped at 101
120
120
  2 usage error
121
121
  130 interrupted with Ctrl-C ( 128+S after SIGTERM / SIGHUP )
122
- 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows, untested there )
122
+ 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows )
123
123
  ```
124
124
 
125
125
  ### Examples
@@ -193,7 +193,7 @@ mcmd --shell -m 4 "dmesg | tail -n 5" "journalctl -n 5 > /tmp/j.log"
193
193
  | Several commands | the number that failed, capped at `101` |
194
194
  | Usage error (bad option, unbalanced quote, no commands) | `2` |
195
195
  | Ctrl-C | `130` (`128+N` after SIGTERM / SIGHUP) |
196
- | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows (untested there) |
196
+ | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows |
197
197
 
198
198
  ### Input files and templates
199
199
 
@@ -445,9 +445,14 @@ and `AsyncExecutor.wait()` included, stops every command, skips the queued ones
445
445
  re-raises, giving them up to 5 s to exit; a second Ctrl-C ends that wait at once. `mcmd` stops its
446
446
  commands on SIGTERM / SIGHUP (unless started with them ignored, as under `nohup`), and when its stdout
447
447
  has no reader (`mcmd ... | head`): it stops them as a Ctrl-C does, and ends by SIGPIPE, as `yes | head` does, with
448
- nothing on stderr. It learns that stdout has no reader only when a write to it fails, so a command that prints nothing
449
- more runs to its end first (`mcmd 'sleep 4' | head -2` takes 4 s, as `sleep 4 | head -2` does). A program that imports
450
- multiCMD still gets the `BrokenPipeError`. At interpreter exit
448
+ nothing on stderr. When stdout is a pipe on Linux and macOS it also asks the pipe as it waits, so a command that prints
449
+ nothing more is stopped as well (`mcmd 'sleep 4' | head -2` ends at once); with any other stdout, and on Windows, it
450
+ learns it only when a write fails, and a command that prints nothing more runs to its end first. ksh93 on Linux builds its
451
+ pipelines from sockets, so under it `mcmd ... | head` is the same: a write finds the reader gone, as in 1.61 (bash, dash, zsh,
452
+ mksh, busybox and macOS's ksh give a pipe). A run that must outlive whatever reads its stdout (a terminal that hangs up, or
453
+ under `nohup` or over `ssh`, where `nohup` leaves a stdout that is not a terminal alone) needs its stdout sent to a file or
454
+ `/dev/null`: `nohup mcmd -q ... > log 2>&1 &`. A program that imports multiCMD still gets the
455
+ write's error (`BrokenPipeError`; `OSError` EINVAL on Windows). At interpreter exit
451
456
  the commands still running are killed, and a command queued on one of multiCMD's threads fails (-1,
452
457
  "not started: the interpreter is exiting") instead of outliving the program; one run from an `atexit`
453
458
  handler after that, on the main thread, runs as usual. A program that handles SIGTERM itself, or runs
@@ -532,6 +537,27 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
532
537
 
533
538
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
534
539
 
540
+ ## Upgrading to 1.62 from 1.61
541
+
542
+ - Nothing needs doing to upgrade, except for a run that must outlive whatever reads its stdout, such as
543
+ `ssh host 'nohup mcmd -q "job" &'` (`nohup` redirects only a stdout that is a terminal, so the pipe to sshd stays): it
544
+ now stops when that pipe's reader quits, where 1.61 ran it to its end. Send its stdout to a file or `/dev/null`:
545
+ `nohup mcmd -q "job" > log 2>&1 &`.
546
+ - Fix: `mcmd` notices a reader that quit while its commands print nothing. When stdout is a pipe on Linux and macOS, the
547
+ waits for the commands ask it each step (`poll()`: POLLERR on Linux, POLLHUP on macOS), so `mcmd 'sleep 4' | head -2`, and
548
+ a `-q` run or one under `-t` whose reader quits, stop their commands at once and end 141, where 1.61 waited for the
549
+ commands to end. Only a pipe is asked. With any other stdout (a file, `/dev/null`, a terminal, a socket) 1.62 asks nothing
550
+ and, on Linux and macOS, does what 1.61 did. Windows has no such poll: it acts on a failed write there too.
551
+ - Fix, Windows: a closed stdout (`mcmd ... | head`) ends `mcmd` with exit status 1 and an empty stderr, as planned in 1.61.
552
+ Windows reports a write to a pipe whose reader quit as `OSError` EINVAL, not `BrokenPipeError`, so 1.61 printed a traceback
553
+ from each reader and exited 120 (seen on GitHub's windows-latest with Python 3.9, 3.12 and 3.14, in Git Bash and cmd pipes;
554
+ once 127 with "Fatal Python error" on 3.14). `mcmd` takes EINVAL from a write to any stdout, not only a pipe, as a reader
555
+ that quit. The library's functions treat that `OSError` as 1.61 did.
556
+ - Fix: `print_progress_bar` no longer raises `UnicodeEncodeError` on a stdout that cannot write its bar (Python 3.6 in a
557
+ C locale, whose stdout is ASCII: hpcp's progress line), or a file name in its prefix (one that is not valid UTF-8, on a
558
+ UTF-8 stdout). The bar's blocks are then drawn in ASCII (`.:-=+*%#`) and what else cannot be written becomes `?`. The
559
+ same in 1.59 to 1.61.
560
+
535
561
  ## Upgrading to 1.61 from 1.60
536
562
 
537
563
  - Nothing needs doing to upgrade.
@@ -540,8 +566,8 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
540
566
  or one that ignores SIGPIPE, ran to its end or for ever, with `mcmd` waiting for it. Now `mcmd` stops the commands as a
541
567
  Ctrl-C does, and ends by SIGPIPE, as `yes | head` does: a shell reports 141, and stderr stays empty (exit status 1 on
542
568
  Windows, untested: a closed pipe may show there as an `OSError` that `mcmd` does not catch yet, planned for 1.62). It
543
- covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions still raise
544
- `BrokenPipeError` when `sys.stdout` fails. A thread that finds stdout closed only says so, and the main thread's
569
+ covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions treat a
570
+ `BrokenPipeError` from `sys.stdout` as 1.60 did. A thread that finds stdout closed only says so, and the main thread's
545
571
  waits stop the commands at their next step (at most 0.1 s later), while a command not started yet is skipped;
546
572
  `mcmd` leaves SIGPIPE ignored, as Python does, so no signal handler's raise can land inside `Popen` or where Python
547
573
  drops it. `mcmd` learns that stdout has no reader only when a write to it fails: a command that prints nothing after
@@ -93,7 +93,7 @@ exit status:
93
93
  N several commands: how many failed, capped at 101
94
94
  2 usage error
95
95
  130 interrupted with Ctrl-C ( 128+S after SIGTERM / SIGHUP )
96
- 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows, untested there )
96
+ 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows )
97
97
  ```
98
98
 
99
99
  ### Examples
@@ -167,7 +167,7 @@ mcmd --shell -m 4 "dmesg | tail -n 5" "journalctl -n 5 > /tmp/j.log"
167
167
  | Several commands | the number that failed, capped at `101` |
168
168
  | Usage error (bad option, unbalanced quote, no commands) | `2` |
169
169
  | Ctrl-C | `130` (`128+N` after SIGTERM / SIGHUP) |
170
- | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows (untested there) |
170
+ | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows |
171
171
 
172
172
  ### Input files and templates
173
173
 
@@ -419,9 +419,14 @@ and `AsyncExecutor.wait()` included, stops every command, skips the queued ones
419
419
  re-raises, giving them up to 5 s to exit; a second Ctrl-C ends that wait at once. `mcmd` stops its
420
420
  commands on SIGTERM / SIGHUP (unless started with them ignored, as under `nohup`), and when its stdout
421
421
  has no reader (`mcmd ... | head`): it stops them as a Ctrl-C does, and ends by SIGPIPE, as `yes | head` does, with
422
- nothing on stderr. It learns that stdout has no reader only when a write to it fails, so a command that prints nothing
423
- more runs to its end first (`mcmd 'sleep 4' | head -2` takes 4 s, as `sleep 4 | head -2` does). A program that imports
424
- multiCMD still gets the `BrokenPipeError`. At interpreter exit
422
+ nothing on stderr. When stdout is a pipe on Linux and macOS it also asks the pipe as it waits, so a command that prints
423
+ nothing more is stopped as well (`mcmd 'sleep 4' | head -2` ends at once); with any other stdout, and on Windows, it
424
+ learns it only when a write fails, and a command that prints nothing more runs to its end first. ksh93 on Linux builds its
425
+ pipelines from sockets, so under it `mcmd ... | head` is the same: a write finds the reader gone, as in 1.61 (bash, dash, zsh,
426
+ mksh, busybox and macOS's ksh give a pipe). A run that must outlive whatever reads its stdout (a terminal that hangs up, or
427
+ under `nohup` or over `ssh`, where `nohup` leaves a stdout that is not a terminal alone) needs its stdout sent to a file or
428
+ `/dev/null`: `nohup mcmd -q ... > log 2>&1 &`. A program that imports multiCMD still gets the
429
+ write's error (`BrokenPipeError`; `OSError` EINVAL on Windows). At interpreter exit
425
430
  the commands still running are killed, and a command queued on one of multiCMD's threads fails (-1,
426
431
  "not started: the interpreter is exiting") instead of outliving the program; one run from an `atexit`
427
432
  handler after that, on the main thread, runs as usual. A program that handles SIGTERM itself, or runs
@@ -506,6 +511,27 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
506
511
 
507
512
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
508
513
 
514
+ ## Upgrading to 1.62 from 1.61
515
+
516
+ - Nothing needs doing to upgrade, except for a run that must outlive whatever reads its stdout, such as
517
+ `ssh host 'nohup mcmd -q "job" &'` (`nohup` redirects only a stdout that is a terminal, so the pipe to sshd stays): it
518
+ now stops when that pipe's reader quits, where 1.61 ran it to its end. Send its stdout to a file or `/dev/null`:
519
+ `nohup mcmd -q "job" > log 2>&1 &`.
520
+ - Fix: `mcmd` notices a reader that quit while its commands print nothing. When stdout is a pipe on Linux and macOS, the
521
+ waits for the commands ask it each step (`poll()`: POLLERR on Linux, POLLHUP on macOS), so `mcmd 'sleep 4' | head -2`, and
522
+ a `-q` run or one under `-t` whose reader quits, stop their commands at once and end 141, where 1.61 waited for the
523
+ commands to end. Only a pipe is asked. With any other stdout (a file, `/dev/null`, a terminal, a socket) 1.62 asks nothing
524
+ and, on Linux and macOS, does what 1.61 did. Windows has no such poll: it acts on a failed write there too.
525
+ - Fix, Windows: a closed stdout (`mcmd ... | head`) ends `mcmd` with exit status 1 and an empty stderr, as planned in 1.61.
526
+ Windows reports a write to a pipe whose reader quit as `OSError` EINVAL, not `BrokenPipeError`, so 1.61 printed a traceback
527
+ from each reader and exited 120 (seen on GitHub's windows-latest with Python 3.9, 3.12 and 3.14, in Git Bash and cmd pipes;
528
+ once 127 with "Fatal Python error" on 3.14). `mcmd` takes EINVAL from a write to any stdout, not only a pipe, as a reader
529
+ that quit. The library's functions treat that `OSError` as 1.61 did.
530
+ - Fix: `print_progress_bar` no longer raises `UnicodeEncodeError` on a stdout that cannot write its bar (Python 3.6 in a
531
+ C locale, whose stdout is ASCII: hpcp's progress line), or a file name in its prefix (one that is not valid UTF-8, on a
532
+ UTF-8 stdout). The bar's blocks are then drawn in ASCII (`.:-=+*%#`) and what else cannot be written becomes `?`. The
533
+ same in 1.59 to 1.61.
534
+
509
535
  ## Upgrading to 1.61 from 1.60
510
536
 
511
537
  - Nothing needs doing to upgrade.
@@ -514,8 +540,8 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
514
540
  or one that ignores SIGPIPE, ran to its end or for ever, with `mcmd` waiting for it. Now `mcmd` stops the commands as a
515
541
  Ctrl-C does, and ends by SIGPIPE, as `yes | head` does: a shell reports 141, and stderr stays empty (exit status 1 on
516
542
  Windows, untested: a closed pipe may show there as an `OSError` that `mcmd` does not catch yet, planned for 1.62). It
517
- covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions still raise
518
- `BrokenPipeError` when `sys.stdout` fails. A thread that finds stdout closed only says so, and the main thread's
543
+ covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions treat a
544
+ `BrokenPipeError` from `sys.stdout` as 1.60 did. A thread that finds stdout closed only says so, and the main thread's
519
545
  waits stop the commands at their next step (at most 0.1 s later), while a command not started yet is skipped;
520
546
  `mcmd` leaves SIGPIPE ignored, as Python does, so no signal handler's raise can land inside `Popen` or where Python
521
547
  drops it. `mcmd` learns that stdout has no reader only when a write to it fails: a command that prints nothing after
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.61
3
+ Version: 1.62
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -119,7 +119,7 @@ exit status:
119
119
  N several commands: how many failed, capped at 101
120
120
  2 usage error
121
121
  130 interrupted with Ctrl-C ( 128+S after SIGTERM / SIGHUP )
122
- 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows, untested there )
122
+ 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows )
123
123
  ```
124
124
 
125
125
  ### Examples
@@ -193,7 +193,7 @@ mcmd --shell -m 4 "dmesg | tail -n 5" "journalctl -n 5 > /tmp/j.log"
193
193
  | Several commands | the number that failed, capped at `101` |
194
194
  | Usage error (bad option, unbalanced quote, no commands) | `2` |
195
195
  | Ctrl-C | `130` (`128+N` after SIGTERM / SIGHUP) |
196
- | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows (untested there) |
196
+ | stdout has no reader (`mcmd ... \| head`) | ended by SIGPIPE, which a shell reports as `141`; `1` on Windows |
197
197
 
198
198
  ### Input files and templates
199
199
 
@@ -445,9 +445,14 @@ and `AsyncExecutor.wait()` included, stops every command, skips the queued ones
445
445
  re-raises, giving them up to 5 s to exit; a second Ctrl-C ends that wait at once. `mcmd` stops its
446
446
  commands on SIGTERM / SIGHUP (unless started with them ignored, as under `nohup`), and when its stdout
447
447
  has no reader (`mcmd ... | head`): it stops them as a Ctrl-C does, and ends by SIGPIPE, as `yes | head` does, with
448
- nothing on stderr. It learns that stdout has no reader only when a write to it fails, so a command that prints nothing
449
- more runs to its end first (`mcmd 'sleep 4' | head -2` takes 4 s, as `sleep 4 | head -2` does). A program that imports
450
- multiCMD still gets the `BrokenPipeError`. At interpreter exit
448
+ nothing on stderr. When stdout is a pipe on Linux and macOS it also asks the pipe as it waits, so a command that prints
449
+ nothing more is stopped as well (`mcmd 'sleep 4' | head -2` ends at once); with any other stdout, and on Windows, it
450
+ learns it only when a write fails, and a command that prints nothing more runs to its end first. ksh93 on Linux builds its
451
+ pipelines from sockets, so under it `mcmd ... | head` is the same: a write finds the reader gone, as in 1.61 (bash, dash, zsh,
452
+ mksh, busybox and macOS's ksh give a pipe). A run that must outlive whatever reads its stdout (a terminal that hangs up, or
453
+ under `nohup` or over `ssh`, where `nohup` leaves a stdout that is not a terminal alone) needs its stdout sent to a file or
454
+ `/dev/null`: `nohup mcmd -q ... > log 2>&1 &`. A program that imports multiCMD still gets the
455
+ write's error (`BrokenPipeError`; `OSError` EINVAL on Windows). At interpreter exit
451
456
  the commands still running are killed, and a command queued on one of multiCMD's threads fails (-1,
452
457
  "not started: the interpreter is exiting") instead of outliving the program; one run from an `atexit`
453
458
  handler after that, on the main thread, runs as usual. A program that handles SIGTERM itself, or runs
@@ -532,6 +537,27 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
532
537
 
533
538
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
534
539
 
540
+ ## Upgrading to 1.62 from 1.61
541
+
542
+ - Nothing needs doing to upgrade, except for a run that must outlive whatever reads its stdout, such as
543
+ `ssh host 'nohup mcmd -q "job" &'` (`nohup` redirects only a stdout that is a terminal, so the pipe to sshd stays): it
544
+ now stops when that pipe's reader quits, where 1.61 ran it to its end. Send its stdout to a file or `/dev/null`:
545
+ `nohup mcmd -q "job" > log 2>&1 &`.
546
+ - Fix: `mcmd` notices a reader that quit while its commands print nothing. When stdout is a pipe on Linux and macOS, the
547
+ waits for the commands ask it each step (`poll()`: POLLERR on Linux, POLLHUP on macOS), so `mcmd 'sleep 4' | head -2`, and
548
+ a `-q` run or one under `-t` whose reader quits, stop their commands at once and end 141, where 1.61 waited for the
549
+ commands to end. Only a pipe is asked. With any other stdout (a file, `/dev/null`, a terminal, a socket) 1.62 asks nothing
550
+ and, on Linux and macOS, does what 1.61 did. Windows has no such poll: it acts on a failed write there too.
551
+ - Fix, Windows: a closed stdout (`mcmd ... | head`) ends `mcmd` with exit status 1 and an empty stderr, as planned in 1.61.
552
+ Windows reports a write to a pipe whose reader quit as `OSError` EINVAL, not `BrokenPipeError`, so 1.61 printed a traceback
553
+ from each reader and exited 120 (seen on GitHub's windows-latest with Python 3.9, 3.12 and 3.14, in Git Bash and cmd pipes;
554
+ once 127 with "Fatal Python error" on 3.14). `mcmd` takes EINVAL from a write to any stdout, not only a pipe, as a reader
555
+ that quit. The library's functions treat that `OSError` as 1.61 did.
556
+ - Fix: `print_progress_bar` no longer raises `UnicodeEncodeError` on a stdout that cannot write its bar (Python 3.6 in a
557
+ C locale, whose stdout is ASCII: hpcp's progress line), or a file name in its prefix (one that is not valid UTF-8, on a
558
+ UTF-8 stdout). The bar's blocks are then drawn in ASCII (`.:-=+*%#`) and what else cannot be written becomes `?`. The
559
+ same in 1.59 to 1.61.
560
+
535
561
  ## Upgrading to 1.61 from 1.60
536
562
 
537
563
  - Nothing needs doing to upgrade.
@@ -540,8 +566,8 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
540
566
  or one that ignores SIGPIPE, ran to its end or for ever, with `mcmd` waiting for it. Now `mcmd` stops the commands as a
541
567
  Ctrl-C does, and ends by SIGPIPE, as `yes | head` does: a shell reports 141, and stderr stays empty (exit status 1 on
542
568
  Windows, untested: a closed pipe may show there as an `OSError` that `mcmd` does not catch yet, planned for 1.62). It
543
- covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions still raise
544
- `BrokenPipeError` when `sys.stdout` fails. A thread that finds stdout closed only says so, and the main thread's
569
+ covers the commands' output, the summary, `--dry-run`, `-h` and `-V`. The library's functions treat a
570
+ `BrokenPipeError` from `sys.stdout` as 1.60 did. A thread that finds stdout closed only says so, and the main thread's
545
571
  waits stop the commands at their next step (at most 0.1 s later), while a command not started yet is skipped;
546
572
  `mcmd` leaves SIGPIPE ignored, as Python does, so no signal handler's raise can land inside `Popen` or where Python
547
573
  drops it. `mcmd` learns that stdout has no reader only when a write to it fails: a command that prints nothing after
@@ -19,6 +19,7 @@ import select
19
19
  import shlex
20
20
  import shutil
21
21
  import signal
22
+ import stat
22
23
  import string
23
24
  import subprocess
24
25
  import sys
@@ -28,7 +29,7 @@ import traceback
28
29
  from pprint import pformat
29
30
 
30
31
  #%% global vars
31
- version = '1.61'
32
+ version = '1.62'
32
33
  __version__ = version
33
34
  COMMIT_DATE = '2026-11-11'
34
35
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
@@ -453,12 +454,14 @@ class _Display:
453
454
  line. redrawable is True when that last line ended with '\r': the next line that replaces a
454
455
  '\r' line, from any command, then overwrites it in place, and anything else starts a new line.
455
456
 
456
- A write that finds stdout without a reader ( BrokenPipeError ) raises it, as any write does, unless on_closed is set,
457
+ A write that finds stdout without a reader ( see _no_reader ) raises, as any write does, unless on_closed is set,
457
458
  as the CLI does ( main() ): then it is closed for good, on_closed is called once, in the thread that found it, and
458
459
  every later write is dropped.
459
460
  @attributes:
460
461
  on_closed: Called, without arguments, by the thread whose write found stdout closed ( None: the write raises )
461
- closed: Whether a write found stdout closed with on_closed set
462
+ closed: Whether a write found stdout closed with on_closed set, or watch saw its reader quit
463
+ watch: A select.poll() with stdout's descriptor in it, that the main thread's waits ask whether the reader quit
464
+ ( see _raise_if_stdout_closed; the CLI's, from _watch_stdout ). None: only a write finds out
462
465
  '''
463
466
  def __init__(self):
464
467
  self.lock = threading.Lock()
@@ -466,6 +469,7 @@ class _Display:
466
469
  self.at_line_start = True
467
470
  self.on_closed = None
468
471
  self.closed = False
472
+ self.watch = None
469
473
 
470
474
  def _write(self, text):
471
475
  '''
@@ -476,8 +480,8 @@ class _Display:
476
480
  try:
477
481
  sys.stdout.write(text)
478
482
  sys.stdout.flush()
479
- except BrokenPipeError:
480
- if self.on_closed is None:
483
+ except OSError as e:
484
+ if self.on_closed is None or not _no_reader(e):
481
485
  raise
482
486
  self.closed = True
483
487
  self.on_closed()
@@ -527,15 +531,54 @@ class _Display:
527
531
 
528
532
  _display = _Display()
529
533
 
534
+ def _no_reader(error):
535
+ '''
536
+ Whether an OSError from a write to stdout says its reader quit ( internal ): BrokenPipeError, or on Windows EINVAL, which
537
+ Windows reports for a write to a pipe whose reader closed it ( seen with Python 3.9, 3.12 and 3.14 )
538
+ '''
539
+ return isinstance(error, BrokenPipeError) or (not _IS_POSIX and error.errno == errno.EINVAL)
540
+
541
+ # what poll() reports for a pipe whose reader closed it: POLLERR on Linux, POLLHUP on macOS ( not POLLNVAL, which poll answers
542
+ # for a descriptor that is not open )
543
+ _READER_QUIT = getattr(select, 'POLLERR', 0) | getattr(select, 'POLLHUP', 0)
544
+
545
+ def _watch_stdout():
546
+ '''
547
+ A select.poll() that tells whether stdout's reader quit, for _Display.watch ( internal ); None unless stdout is a pipe
548
+ ( `mcmd ... | head`; a named FIFO too ) and select.poll exists ( not on Windows )
549
+ Only a pipe is asked: POLLHUP is also what a terminal answers once it hung up, which a job left running on purpose
550
+ ( `mcmd ... &` then `exit` or `disown`, or `setsid mcmd ...` ) outlives, and what macOS answers for a socket whose peer only
551
+ half-closed ( shutdown( SHUT_WR ), as socat or an HTTP/1.0 client does ) while it is still reading. For those, a write
552
+ that fails still finds a reader that quit.
553
+ '''
554
+ if not hasattr(select, 'poll'):
555
+ return None
556
+ try:
557
+ fd = sys.stdout.fileno()
558
+ if not stat.S_ISFIFO(os.fstat(fd).st_mode):
559
+ return None
560
+ except (AttributeError, OSError, ValueError):
561
+ return None
562
+ watch = select.poll()
563
+ watch.register(fd, _READER_QUIT)
564
+ return watch
565
+
530
566
  def _raise_if_stdout_closed():
531
567
  '''
532
- Raise _StdoutClosed in the main thread if a write found stdout closed, as the CLI's waits for its commands do ( internal )
533
- A reader or pool worker that finds it only sets _display.closed ( see _stdout_closed ); the main thread, which is the one
534
- that stops the commands, looks at each step of its waits ( _watch, _drain, the pool's join loop ). The waits of a stop do
535
- not look: it is raised once, before the stop begins. A command not started yet is skipped meanwhile ( __run_command: before
536
- its header and again after it, as that write raises nothing on a worker thread ).
568
+ Raise _StdoutClosed in the main thread if stdout has no reader any more, as the CLI's waits for its commands do ( internal )
569
+ A reader or pool worker whose write finds it only sets _display.closed ( see _stdout_closed ); the main thread, which is the
570
+ one that stops the commands, looks at each step of its waits ( _watch, _drain, the pool's join loop ), and asks
571
+ _display.watch too, if set, so a reader that quits while the commands print nothing ends the run as well. The waits of a
572
+ stop do not look: it is raised once, before the stop begins. A command not started yet is skipped meanwhile ( __run_command:
573
+ before its header and again after it, as that write raises nothing on a worker thread ).
537
574
  '''
538
- if _display.closed and _thread.get_ident() == threading.main_thread().ident:
575
+ if _thread.get_ident() != threading.main_thread().ident:
576
+ return
577
+ if not _display.closed and _display.watch is not None:
578
+ for _, events in _display.watch.poll(0):
579
+ if events & _READER_QUIT:
580
+ _display.closed = True
581
+ if _display.closed:
539
582
  raise _StdoutClosed()
540
583
 
541
584
  class AsyncExecutor:
@@ -2819,7 +2862,7 @@ _EXIT_STATUS_HELP = '''exit status:
2819
2862
  N several commands: how many failed, capped at 101
2820
2863
  2 usage error
2821
2864
  130 interrupted with Ctrl-C ( 128+S after SIGTERM / SIGHUP )
2822
- 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows, untested there )'''
2865
+ 141 stdout closed ( `mcmd ... | head` ): commands stopped, ended by SIGPIPE ( 1 on Windows )'''
2823
2866
 
2824
2867
  def _exit_status(tasks):
2825
2868
  '''
@@ -3008,11 +3051,12 @@ def main():
3008
3051
  '''
3009
3052
  The command line ( see _run_cli ). Output that nobody reads any more ( `mcmd ... | head` ) is taken as an interrupt: every
3010
3053
  command is stopped, as a Ctrl-C stops them, and the process ends by SIGPIPE with nothing on stderr
3011
- ( _end_by_closed_stdout ). The library's functions keep raising BrokenPipeError as they did.
3054
+ ( _end_by_closed_stdout ). The library's functions keep raising what the write raised ( BrokenPipeError ), as they did.
3012
3055
  @returns:
3013
3056
  int: The exit status
3014
3057
  '''
3015
3058
  _display.on_closed = _stdout_closed
3059
+ _display.watch = _watch_stdout()
3016
3060
  try:
3017
3061
  try:
3018
3062
  status = _run_cli()
@@ -3021,15 +3065,18 @@ def main():
3021
3065
  if sys.stdout is not None:
3022
3066
  try:
3023
3067
  sys.stdout.flush()
3024
- except BrokenPipeError:
3025
- raise
3026
- except OSError:
3068
+ except OSError as e:
3069
+ if _no_reader(e):
3070
+ raise
3027
3071
  # a full disk, an I/O error: Python's own flush at exit says so, as it did before the CLI flushed itself
3028
- pass
3029
3072
  if _display.closed:
3030
3073
  # a reader found it closed as the run ended, and no wait looked again
3031
3074
  raise _StdoutClosed()
3032
- except (BrokenPipeError, _StdoutClosed):
3075
+ except _StdoutClosed:
3076
+ _end_by_closed_stdout()
3077
+ except OSError as e:
3078
+ if not _no_reader(e):
3079
+ raise
3033
3080
  _end_by_closed_stdout()
3034
3081
  return status
3035
3082
 
@@ -3342,6 +3389,10 @@ def get_terminal_size():
3342
3389
  _tsize = shutil.get_terminal_size(fallback=(240, 50))
3343
3390
  return _tsize
3344
3391
 
3392
+ # the bar's blocks, and what a stdout whose encoding has no such characters gets for them ( see _writable )
3393
+ _BAR_BLOCKS = '▁▂▃▄▅▆▇█'
3394
+ _ASCII_BAR = str.maketrans(_BAR_BLOCKS, '.:-=+*%#')
3395
+
3345
3396
  def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3346
3397
  '''
3347
3398
  Generate a progress bar string
@@ -3379,7 +3430,7 @@ def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3379
3430
  if iteration == 0:
3380
3431
  noBar = True
3381
3432
  filled_length = int(length * iteration // total)
3382
- progress_chars = '▁▂▃▄▅▆▇█'
3433
+ progress_chars = _BAR_BLOCKS
3383
3434
  fractional_progress = (length * iteration / total) - filled_length
3384
3435
  char_index = int(fractional_progress * (len(progress_chars) - 1))
3385
3436
  bar_char = progress_chars[char_index]
@@ -3401,6 +3452,28 @@ def _genrate_progress_bar(iteration, total, prefix='', suffix='',columns=240):
3401
3452
  lineOut += suffix
3402
3453
  return lineOut
3403
3454
 
3455
+ def _writable(text, stream):
3456
+ '''
3457
+ text as stream can write it ( internal ): unchanged if its encoding takes it ( with the stream's own errors handler ),
3458
+ else with the bar's blocks in ASCII if the encoding has none ( Python 3.6 in a C locale has an ASCII stdout ) and '?' for
3459
+ whatever else it cannot write ( a file name that is not valid UTF-8, on a UTF-8 stdout )
3460
+ '''
3461
+ encoding = getattr(stream, 'encoding', None)
3462
+ if not encoding:
3463
+ return text
3464
+ try:
3465
+ text.encode(encoding, getattr(stream, 'errors', None) or 'strict')
3466
+ return text
3467
+ except UnicodeEncodeError:
3468
+ pass
3469
+ except LookupError:
3470
+ return text
3471
+ try:
3472
+ _BAR_BLOCKS.encode(encoding)
3473
+ except UnicodeEncodeError:
3474
+ text = text.translate(_ASCII_BAR)
3475
+ return text.encode(encoding, 'replace').decode(encoding)
3476
+
3404
3477
  def print_progress_bar(iteration, total, prefix='', suffix=''):
3405
3478
  '''
3406
3479
  Call in a loop to create terminal progress bar
@@ -3417,13 +3490,13 @@ def print_progress_bar(iteration, total, prefix='', suffix=''):
3417
3490
  suffix = f'| {suffix}' if not suffix.startswith('| ') else suffix
3418
3491
  try:
3419
3492
  columns, _ = get_terminal_size()
3420
- sys.stdout.write(f'\r{_genrate_progress_bar(iteration, total, prefix, suffix, columns)}')
3493
+ sys.stdout.write(_writable(f'\r{_genrate_progress_bar(iteration, total, prefix, suffix, columns)}', sys.stdout))
3421
3494
  sys.stdout.flush()
3422
3495
  if iteration == total and total > 0:
3423
3496
  print(file=sys.stdout)
3424
3497
  except Exception:
3425
3498
  if iteration % 5 == 0:
3426
- print(_genrate_progress_bar(iteration, total, prefix, suffix))
3499
+ print(_writable(_genrate_progress_bar(iteration, total, prefix, suffix), sys.stdout))
3427
3500
 
3428
3501
  def format_bytes(size, use_1024_bytes=None, to_int=False, to_str=False, str_format=".2f"):
3429
3502
  if to_int or isinstance(size, str):
@@ -3,9 +3,12 @@
3
3
  ( by SIGPIPE, the shell's 141 ), after the commands it started were stopped. Python's own answer to a stdout it cannot
4
4
  flush is a traceback, "Exception ignored" and exit status 120.
5
5
  '''
6
+ import errno
6
7
  import os
8
+ import select
7
9
  import shlex
8
10
  import signal
11
+ import socket
9
12
  import subprocess
10
13
  import sys
11
14
  import threading
@@ -17,6 +20,7 @@ from conftest import MULTICMD_PY, pid_gone
17
20
  import multiCMD
18
21
 
19
22
  posix_only = pytest.mark.skipif(os.name != 'posix', reason='SIGPIPE: POSIX only')
23
+ has_poll = pytest.mark.skipif(not hasattr(select, 'poll'), reason='needs select.poll')
20
24
 
21
25
 
22
26
  def start_cli(args, driver=None, **fields):
@@ -447,3 +451,275 @@ def test_main_leaves_a_working_stdout_alone(monkeypatch):
447
451
  monkeypatch.setattr(multiCMD, '_run_cli', lambda: 5)
448
452
  assert multiCMD.main() == 5
449
453
  assert ended == []
454
+
455
+
456
+ # stdout polled: a reader that quits ends the run though nothing is written ( 1.61 found out only from a write, and the
457
+ # commands ran to their end first )
458
+
459
+
460
+ @posix_only
461
+ @has_poll
462
+ @pytest.mark.parametrize('options, count', [
463
+ pytest.param([], 1, id='serial'),
464
+ pytest.param(['-q'], 1, id='quiet'),
465
+ pytest.param(['-t', '30'], 1, id='timeout'),
466
+ pytest.param(['-q', '-m', '2'], 2, id='pool'),
467
+ ])
468
+ def test_a_reader_that_quits_while_the_commands_print_nothing_ends_the_cli_at_once(tmp_path, options, count):
469
+ # ( `mcmd 'sleep 4' | head -2`: 1.61 waited the 4 s, 12 here )
470
+ commands = [f'sh -c {shlex.quote(f"echo $$ > {tmp_path}/pid{i}; exec sleep 12")}' for i in range(1, count + 1)]
471
+ proc = start_cli(options + commands)
472
+ try:
473
+ wait_for_pidfiles(tmp_path, count)
474
+ closed = time.monotonic()
475
+ proc.reader.close()
476
+ status, err = finish(proc)
477
+ took = time.monotonic() - closed
478
+ assert status == -signal.SIGPIPE
479
+ assert err == ''
480
+ # ( the stop itself takes about 10 ms: SIGINT ends sleep )
481
+ assert took < 6
482
+ assert all(pid_gone(pid) for pid in pids_in(tmp_path))
483
+ finally:
484
+ proc.reader.close()
485
+ kill_leftovers(pids_in(tmp_path))
486
+
487
+
488
+ def run_cli_quiet(stdout, command):
489
+ '''The CLI, quiet, with the given stdout ( a file ), run to its end'''
490
+ return subprocess.run([sys.executable, str(MULTICMD_PY), '-q', command], stdin=subprocess.DEVNULL, stdout=stdout,
491
+ stderr=subprocess.PIPE, universal_newlines=True, timeout=30)
492
+
493
+
494
+ @posix_only
495
+ @pytest.mark.parametrize('target', ['devnull', 'file'])
496
+ def test_a_stdout_that_is_not_a_pipe_is_not_taken_for_one_whose_reader_quit(tmp_path, target):
497
+ path = os.devnull if target == 'devnull' else str(tmp_path / 'out')
498
+ with open(path, 'wb') as out:
499
+ proc = run_cli_quiet(out, 'sleep 0.3')
500
+ assert proc.returncode == 0
501
+ assert proc.stderr == ''
502
+
503
+
504
+ @posix_only
505
+ @has_poll
506
+ def test_a_terminal_that_hung_up_is_not_taken_for_a_reader_that_quit(tmp_path):
507
+ # `mcmd 'long job' &` then `exit` or `disown`, or `setsid mcmd 'long job'`: the terminal goes, poll() answers POLLHUP for its slave, and
508
+ # the shell and the kernel send the job no signal. 1.62 first stopped it ( 141 ); a job left running on purpose runs on
509
+ import pty
510
+ master, slave = pty.openpty()
511
+ command = 'sh -c ' + shlex.quote(f'echo $$ > {tmp_path}/pid1; sleep 0.6; touch {tmp_path}/done')
512
+ try:
513
+ proc = subprocess.Popen([sys.executable, str(MULTICMD_PY), '-q', command], stdin=subprocess.DEVNULL, stdout=slave,
514
+ stderr=subprocess.PIPE, start_new_session=True)
515
+ os.close(slave)
516
+ slave = -1
517
+ try:
518
+ wait_for_pidfiles(tmp_path, 1)
519
+ os.close(master)
520
+ master = -1
521
+ status, err = finish(proc)
522
+ finally:
523
+ proc.kill()
524
+ kill_leftovers(pids_in(tmp_path))
525
+ finally:
526
+ for fd in (master, slave):
527
+ if fd >= 0:
528
+ os.close(fd)
529
+ assert (status, err) == (0, '')
530
+ assert (tmp_path / 'done').exists()
531
+
532
+
533
+ @posix_only
534
+ @has_poll
535
+ def test_a_socket_whose_peer_half_closed_is_not_taken_for_a_reader_that_quit():
536
+ # `socat - TCP:host:port` or an HTTP/1.0 client sends its request, calls shutdown(SHUT_WR) and reads the reply: macOS
537
+ # answers POLLHUP for the server side of it though the client is reading ( Linux sets POLLHUP on a connected socket only
538
+ # once both directions are shut, so there this checks only that the reply gets through )
539
+ client, served = socket.socketpair()
540
+ try:
541
+ client.shutdown(socket.SHUT_WR)
542
+ client.settimeout(30)
543
+ proc = subprocess.Popen([sys.executable, str(MULTICMD_PY), "sh -c 'sleep 0.5; echo RESULT'"], stdin=subprocess.DEVNULL,
544
+ stdout=served.fileno(), stderr=subprocess.PIPE, universal_newlines=True)
545
+ served.close()
546
+ reply = b''
547
+ try:
548
+ while True:
549
+ data = client.recv(65536)
550
+ if not data:
551
+ break
552
+ reply += data
553
+ finally:
554
+ err = proc.communicate(timeout=30)[1]
555
+ finally:
556
+ client.close()
557
+ served.close()
558
+ assert proc.returncode == 0
559
+ assert err == ''
560
+ assert b'RESULT' in reply
561
+
562
+
563
+ @posix_only
564
+ @pytest.mark.skipif(not sys.platform.startswith('linux'), reason='macOS does not tell a named FIFO that its reader quit')
565
+ def test_a_named_fifo_whose_reader_quits_ends_the_cli_at_once(tmp_path):
566
+ # `mcmd -q ... > fifo`: a FIFO is a pipe to poll, named or not
567
+ fifo = str(tmp_path / 'fifo')
568
+ os.mkfifo(fifo)
569
+ command = 'sh -c ' + shlex.quote(f'echo $$ > {tmp_path}/pid1; exec sleep 12')
570
+ reader = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK)
571
+ try:
572
+ writer = os.open(fifo, os.O_WRONLY)
573
+ try:
574
+ proc = subprocess.Popen([sys.executable, str(MULTICMD_PY), '-q', command], stdin=subprocess.DEVNULL, stdout=writer,
575
+ stderr=subprocess.PIPE)
576
+ finally:
577
+ os.close(writer)
578
+ wait_for_pidfiles(tmp_path, 1)
579
+ closed = time.monotonic()
580
+ os.close(reader)
581
+ reader = -1
582
+ status, err = finish(proc)
583
+ assert (status, err) == (-signal.SIGPIPE, '')
584
+ assert time.monotonic() - closed < 6
585
+ assert all(pid_gone(pid) for pid in pids_in(tmp_path))
586
+ finally:
587
+ if reader >= 0:
588
+ os.close(reader)
589
+ kill_leftovers(pids_in(tmp_path))
590
+
591
+
592
+ class StdoutOn:
593
+ '''A stdout that is a descriptor'''
594
+ def __init__(self, fd):
595
+ self.fd = fd
596
+
597
+ def fileno(self):
598
+ return self.fd
599
+
600
+
601
+ @posix_only
602
+ @has_poll
603
+ def test_only_a_pipe_is_watched_for_a_reader_that_quit(tmp_path, monkeypatch):
604
+ # what poll() says about a terminal ( POLLHUP once it hung up ), a socket ( macOS: POLLHUP once the peer half-closed ) or a
605
+ # device ( macOS: POLLNVAL ) is not a reader that quit; _watch_stdout asks a pipe only
606
+ import pty
607
+ pipe = os.pipe()
608
+ master, slave = pty.openpty()
609
+ sock, peer = socket.socketpair()
610
+ named_fifo = str(tmp_path / 'fifo')
611
+ os.mkfifo(named_fifo)
612
+ opened = [pipe[0], pipe[1], master, slave, os.open(os.devnull, os.O_WRONLY), os.open(str(tmp_path / 'f'), os.O_WRONLY | os.O_CREAT),
613
+ os.open(named_fifo, os.O_RDWR)]
614
+ _, _, _, _, devnull, file, fifo = opened
615
+ try:
616
+ wrong = []
617
+ for name, fd in [('pipe', pipe[1]), ('named FIFO', fifo), ('file', file), ('/dev/null', devnull), ('terminal', slave),
618
+ ('socket', sock.fileno())]:
619
+ monkeypatch.setattr(sys, 'stdout', StdoutOn(fd))
620
+ if (multiCMD._watch_stdout() is not None) != (name in ('pipe', 'named FIFO')):
621
+ wrong.append(name)
622
+ assert wrong == []
623
+ finally:
624
+ for fd in opened:
625
+ os.close(fd)
626
+ sock.close()
627
+ peer.close()
628
+
629
+
630
+ @posix_only
631
+ @has_poll
632
+ def test_a_stdout_that_cannot_be_asked_is_not_watched(monkeypatch):
633
+ read_end, write_end = os.pipe()
634
+ os.close(read_end)
635
+ os.close(write_end)
636
+ monkeypatch.setattr(sys, 'stdout', StdoutOn(write_end))
637
+ assert multiCMD._watch_stdout() is None
638
+ monkeypatch.setattr(sys, 'stdout', object())
639
+ assert multiCMD._watch_stdout() is None
640
+
641
+
642
+ @has_poll
643
+ def test_a_stdout_descriptor_that_is_not_open_is_not_taken_for_a_reader_that_quit():
644
+ # poll answers POLLNVAL for it whatever was asked: only POLLERR ( Linux ) and POLLHUP ( macOS ) say the reader quit
645
+ read_end, write_end = os.pipe()
646
+ watch = select.poll()
647
+ watch.register(write_end, select.POLLERR | select.POLLHUP)
648
+ os.close(read_end)
649
+ os.close(write_end)
650
+ multiCMD._display.watch = watch
651
+ multiCMD._raise_if_stdout_closed()
652
+ assert not multiCMD._display.closed
653
+
654
+
655
+ @has_poll
656
+ def test_the_library_does_not_poll_stdout(monkeypatch):
657
+ # only the CLI is a filter that ends when its reader quits: a program that imports multiCMD, with a pipe for stdout
658
+ # whose reader quit, gets no _StdoutClosed from a quiet run, which writes nothing
659
+ read_end, write_end = os.pipe()
660
+ os.close(read_end)
661
+ pipe = os.fdopen(write_end, 'w')
662
+ monkeypatch.setattr(sys, 'stdout', pipe)
663
+ try:
664
+ status = multiCMD.run_command([sys.executable, '-c', 'import time; time.sleep(0.2)'], quiet=True, return_code_only=True)
665
+ assert status == 0
666
+ assert multiCMD._display.watch is None
667
+ finally:
668
+ monkeypatch.undo()
669
+ try:
670
+ pipe.close()
671
+ except OSError:
672
+ pass
673
+
674
+
675
+ # Windows reports a write to a pipe whose reader quit as OSError EINVAL, not BrokenPipeError ( seen on windows-latest with
676
+ # Python 3.9, 3.12 and 3.14, 2026-11-11 )
677
+
678
+
679
+ class EinvalStdout:
680
+ '''A stdout whose reader quit, as Windows reports it'''
681
+ def write(self, text):
682
+ raise OSError(errno.EINVAL, 'Invalid argument')
683
+
684
+ def flush(self):
685
+ raise OSError(errno.EINVAL, 'Invalid argument')
686
+
687
+
688
+ @pytest.mark.parametrize('posix', [False, True], ids=['windows', 'posix'])
689
+ def test_einval_from_a_stdout_write_is_a_reader_that_quit_on_windows_only(monkeypatch, posix):
690
+ monkeypatch.setattr(multiCMD, '_IS_POSIX', posix)
691
+ monkeypatch.setattr(sys, 'stdout', EinvalStdout())
692
+ called = []
693
+ multiCMD._display.on_closed = lambda: called.append(True)
694
+ if posix:
695
+ with pytest.raises(OSError):
696
+ multiCMD._display.message('x')
697
+ assert not multiCMD._display.closed
698
+ else:
699
+ multiCMD._display.message('x')
700
+ assert multiCMD._display.closed
701
+ assert called == [True]
702
+
703
+
704
+ class Ended(BaseException):
705
+ '''_end_by_closed_stdout, which never returns, was called'''
706
+
707
+
708
+ def end_by_closed_stdout():
709
+ raise Ended()
710
+
711
+
712
+ @pytest.mark.parametrize('where', ['flush', 'run'])
713
+ def test_main_ends_the_process_on_einval_from_stdout_on_windows(monkeypatch, where):
714
+ # the final flush, or argparse writing its help or usage to the closed pipe
715
+ monkeypatch.setattr(multiCMD, '_IS_POSIX', False)
716
+ monkeypatch.setattr(multiCMD, '_end_by_closed_stdout', end_by_closed_stdout)
717
+ if where == 'flush':
718
+ monkeypatch.setattr(multiCMD, '_run_cli', lambda: 0)
719
+ monkeypatch.setattr(sys, 'stdout', EinvalStdout())
720
+ else:
721
+ def run():
722
+ raise OSError(errno.EINVAL, 'Invalid argument')
723
+ monkeypatch.setattr(multiCMD, '_run_cli', run)
724
+ with pytest.raises(Ended):
725
+ multiCMD.main()
@@ -1,4 +1,5 @@
1
1
  import builtins
2
+ import io
2
3
  import os
3
4
  import select
4
5
  import subprocess
@@ -85,6 +86,45 @@ def test_progress_bar_helpers(capsys, monkeypatch):
85
86
  )
86
87
 
87
88
 
89
+ def ascii_stdout(monkeypatch, encoding='ascii', errors='surrogateescape'):
90
+ # Python 3.6 in a C locale ( hpcp's library calls ): an ASCII stdout that takes undecodable file names
91
+ out = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors=errors)
92
+ monkeypatch.setattr(sys, 'stdout', out)
93
+ monkeypatch.setattr("multiCMD.get_terminal_size", lambda: (80, 24))
94
+ return out
95
+
96
+
97
+ def test_progress_bar_on_a_stdout_that_cannot_write_its_blocks(monkeypatch):
98
+ # 1.61 raised UnicodeEncodeError out of the call, from its fallback, which printed the same bar again
99
+ out = ascii_stdout(monkeypatch)
100
+ print_progress_bar(5, 10, prefix="Progress:", suffix="Complete")
101
+ print_progress_bar(10, 10, prefix="Progress:", suffix="Complete")
102
+ out.flush()
103
+ assert out.buffer.getvalue().decode('ascii') == (
104
+ "\rProgress: |" + "#" * 24 + "=" + "_" * 25 + "|50.0% | Complete"
105
+ "\rProgress: |" + "#" * 48 + "|100.0% | Complete\n"
106
+ )
107
+
108
+
109
+ def test_progress_bar_with_a_name_its_stdout_cannot_write(monkeypatch):
110
+ # a file name with a byte that is not UTF-8 ( decoded with surrogateescape ) on a UTF-8 stdout, which is strict
111
+ out = ascii_stdout(monkeypatch, 'utf-8', 'strict')
112
+ print_progress_bar(3, 0, prefix='dir/caf\udce9', suffix='s')
113
+ out.flush()
114
+ assert out.buffer.getvalue().decode('utf-8') == '\r' + 'dir/caf? | iteration:3 | s'.ljust(80)
115
+
116
+
117
+ def test_progress_bar_in_a_c_locale_python():
118
+ # the real stdout of a Python whose locale has no encoding for the bar ( on 3.7+ only PYTHONIOENCODING makes it ASCII )
119
+ code = ('import sys; sys.path.insert(0, %r); import multiCMD; multiCMD.print_progress_bar(5, 10, "p", "s")'
120
+ % str(Path(multiCMD.__file__).parent))
121
+ env = dict(os.environ, LC_ALL='C', LANG='C', PYTHONIOENCODING='ascii')
122
+ proc = subprocess.run([sys.executable, '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, timeout=30)
123
+ assert proc.returncode == 0, proc.stderr
124
+ assert proc.stderr == b''
125
+ assert b'#' in proc.stdout and b'|50.0% | s' in proc.stdout
126
+
127
+
88
128
  def test_get_terminal_size_tuple():
89
129
  cols, rows = get_terminal_size()
90
130
  assert cols > 0 and rows > 0
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
File without changes