Context manager that eases checking for unknown command, without crashing. Example: >>> with ContextManagerSubprocess("tcpdump"): >>> subprocess.Popen(["tcpdump", "--version"]) ERROR: Could not execute tcpdump, is it installed?
| 918 | |
| 919 | |
| 920 | class ContextManagerSubprocess(object): |
| 921 | """ |
| 922 | Context manager that eases checking for unknown command, without |
| 923 | crashing. |
| 924 | |
| 925 | Example: |
| 926 | >>> with ContextManagerSubprocess("tcpdump"): |
| 927 | >>> subprocess.Popen(["tcpdump", "--version"]) |
| 928 | ERROR: Could not execute tcpdump, is it installed? |
| 929 | |
| 930 | """ |
| 931 | |
| 932 | def __init__(self, prog, suppress=True): |
| 933 | # type: (str, bool) -> None |
| 934 | self.prog = prog |
| 935 | self.suppress = suppress |
| 936 | |
| 937 | def __enter__(self): |
| 938 | # type: () -> None |
| 939 | pass |
| 940 | |
| 941 | def __exit__(self, |
| 942 | exc_type, # type: Optional[type] |
| 943 | exc_value, # type: Optional[Exception] |
| 944 | traceback, # type: Optional[Any] |
| 945 | ): |
| 946 | # type: (...) -> Optional[bool] |
| 947 | if exc_value is None or exc_type is None: |
| 948 | return None |
| 949 | # Errored |
| 950 | if isinstance(exc_value, EnvironmentError): |
| 951 | msg = "Could not execute %s, is it installed?" % self.prog |
| 952 | else: |
| 953 | msg = "%s: execution failed (%s)" % ( |
| 954 | self.prog, |
| 955 | exc_type.__class__.__name__ |
| 956 | ) |
| 957 | if not self.suppress: |
| 958 | raise exc_type(msg) |
| 959 | log_runtime.error(msg, exc_info=True) |
| 960 | return True # Suppress the exception |
| 961 | |
| 962 | |
| 963 | class ContextManagerCaptureOutput(object): |