Use subprocess instead of os.system (#1477)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John T. Wodder II · committed by GitHub · parent 70c673d · Browse files · 3 files·+80 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Andreas Backx <andreas@backx.org>
Diff stats
3 files+80 added−32 removed
- tests:+1 added−1 removed
- other:+79 added−31 removed
Provenance
- Commit
299efb8- Tree
daae6a5- Author
John T. Wodder II <jwodder@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
70c673d
3 files changed+80 added−32 removed
modified:src/click/_termui_impl.py+79 added-31 removed
10 unmodified lines11 import time12 import typing as t13 from gettext import gettext as _14 from io import StringIO15+from shutil import which16 from types import TracebackType17 18 from ._compat import _default_text_stdout19 from ._compat import CYGWIN352 unmodified lines372 return _nullpager(stdout, generator, color)373 pager_cmd = (os.environ.get("PAGER", None) or "").strip()374 if pager_cmd:375 if WIN:375- return _tempfilepager(generator, pager_cmd, color)376- return _pipepager(generator, pager_cmd, color)376+ if _tempfilepager(generator, pager_cmd, color):377+ return378+ elif _pipepager(generator, pager_cmd, color):379+ return380 if os.environ.get("TERM") in ("dumb", "emacs"):381 return _nullpager(stdout, generator, color)379- if WIN or sys.platform.startswith("os2"):380- return _tempfilepager(generator, "more <", color)381- if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:382- return _pipepager(generator, "less", color)382+ if (WIN or sys.platform.startswith("os2")) and _tempfilepager(383+ generator, "more", color384+ ):385+ return386+ if _pipepager(generator, "less", color):387+ return388 389 import tempfile390 391 fd, filename = tempfile.mkstemp()392 os.close(fd)393 try:389- if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:390- return _pipepager(generator, "more", color)394+ if _pipepager(generator, "more", color):395+ return396 return _nullpager(stdout, generator, color)397 finally:398 os.unlink(filename)399 400 396-def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:401+def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> bool:402 """Page through text by feeding it to another program. Invoking a403 pager through this might support colors.404+405+ Returns True if the command was found, False otherwise and thus another406+ pager should be attempted.407 """408+ cmd_absolute = which(cmd)409+ if cmd_absolute is None:410+ return False411+412 import subprocess413 414 env = dict(os.environ)415 7 unmodified lines423 color = True424 elif "r" in less_flags or "R" in less_flags:425 color = True426 415- c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)416- stdin = t.cast(t.BinaryIO, c.stdin)417- encoding = get_best_encoding(stdin)427+ c = subprocess.Popen(428+ [cmd_absolute],429+ shell=True,430+ stdin=subprocess.PIPE,431+ env=env,432+ errors="replace",433+ text=True,434+ )435+ assert c.stdin is not None436 try:437 for text in generator:438 if not color:439 text = strip_ansi(text)440 423- stdin.write(text.encode(encoding, "replace"))441+ c.stdin.write(text)442 except (OSError, KeyboardInterrupt):443 pass444 else:427- stdin.close()445+ c.stdin.close()446 447 # Less doesn't respect ^C, but catches it for its own UI purposes (aborting448 # search or other commands inside less).449 #9 unmodified lines459 pass460 else:461 break462 463+ return True464 465+466 def _tempfilepager(447- generator: t.Iterable[str], cmd: str, color: t.Optional[bool]448-) -> None:449- """Page through text by invoking a program on a temporary file."""467+ generator: t.Iterable[str],468+ cmd: str,469+ color: t.Optional[bool],470+) -> bool:471+ """Page through text by invoking a program on a temporary file.472+473+ Returns True if the command was found, False otherwise and thus another474+ pager should be attempted.475+ """476+ # Which is necessary for Windows, it is also recommended in the Popen docs.477+ cmd_absolute = which(cmd)478+ if cmd_absolute is None:479+ return False480+481+ import subprocess482 import tempfile483 484 fd, filename = tempfile.mkstemp()485 # TODO: This never terminates if the passed generator never terminates.3 unmodified lines489 encoding = get_best_encoding(sys.stdout)490 with open_stream(filename, "wb")[0] as f:491 f.write(text.encode(encoding))492 try:461- os.system(f'{cmd} "{filename}"')493+ subprocess.call([cmd_absolute, filename])494+ except OSError:495+ # Command not found496+ pass497 finally:498 os.close(fd)499 os.unlink(filename)500 501+ return True502 503+504 def _nullpager(505 stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]506 ) -> None:507 """Simply print unformatted text. This is the ultimate fallback."""25 unmodified lines533 return rv534 if WIN:535 return "notepad"536 for editor in "sensible-editor", "vim", "nano":500- if os.system(f"which {editor} >/dev/null 2>&1") == 0:537+ if which(editor) is not None:538 return editor539 return "vi"540 541 def edit_file(self, filename: str) -> None:90 unmodified lines632 finally:633 null.close()634 elif WIN:635 if locate:599- url = _unquote_file(url.replace('"', ""))600- args = f'explorer /select,"{url}"'636+ url = _unquote_file(url)637+ args = ["explorer", f"/select,{url}"]638 else:602- url = url.replace('"', "")603- wait_str = "/WAIT" if wait else ""604- args = f'start {wait_str} "" "{url}"'605- return os.system(args)639+ args = ["start"]640+ if wait:641+ args.append("/WAIT")642+ args.append("")643+ args.append(url)644+ try:645+ return subprocess.call(args)646+ except OSError:647+ # Command not found648+ return 127649 elif CYGWIN:650 if locate:608- url = os.path.dirname(_unquote_file(url).replace('"', ""))609- args = f'cygstart "{url}"'651+ url = _unquote_file(url)652+ args = ["cygstart", os.path.dirname(url)]653 else:611- url = url.replace('"', "")612- wait_str = "-w" if wait else ""613- args = f'cygstart {wait_str} "{url}"'614- return os.system(args)654+ args = ["cygstart"]655+ if wait:656+ args.append("-w")657+ args.append(url)658+ try:659+ return subprocess.call(args)660+ except OSError:661+ # Command not found662+ return 127663 664 try:665 if locate:666 url = os.path.dirname(_unquote_file(url)) or "."122 unmodified linesmodified:tests/test_imports.py+1 added
45 unmodified lines46 "enum",47 "typing",48 "types",49 "gettext",50+ "shutil",51 }52 53 if WIN:54 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])14 unmodified linesmodified:tests/test_utils.py-1 removed
177 unmodified lines178 yield "c"179 yield "abc"180 181 182-@pytest.mark.skipif(WIN, reason="Different behavior on windows.")182 @pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])183 @pytest.mark.parametrize(184 "test",185 [325 unmodified lines