Read channel until pattern is detected. Will return string up to and including pattern. Returns ReadTimeout if pattern not detected in read_timeout seconds. :param pattern: Regular expression pattern used to identify that reading is done. :param read_timeout: maxi
(
self,
pattern: str = "",
read_timeout: float = 10.0,
re_flags: int = 0,
max_loops: Optional[int] = None,
)
| 658 | return output |
| 659 | |
| 660 | def read_until_pattern( |
| 661 | self, |
| 662 | pattern: str = "", |
| 663 | read_timeout: float = 10.0, |
| 664 | re_flags: int = 0, |
| 665 | max_loops: Optional[int] = None, |
| 666 | ) -> str: |
| 667 | """Read channel until pattern is detected. |
| 668 | |
| 669 | Will return string up to and including pattern. |
| 670 | |
| 671 | Returns ReadTimeout if pattern not detected in read_timeout seconds. |
| 672 | |
| 673 | :param pattern: Regular expression pattern used to identify that reading is done. |
| 674 | |
| 675 | :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout. |
| 676 | A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep |
| 677 | reading indefinitely until pattern is detected. |
| 678 | |
| 679 | :param re_flags: regex flags used in conjunction with pattern (defaults to no flags). |
| 680 | |
| 681 | :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5. |
| 682 | """ |
| 683 | if max_loops is not None: |
| 684 | msg = """\n |
| 685 | Netmiko 4.x has deprecated the use of max_loops with read_until_pattern. |
| 686 | You should convert all uses of max_loops over to read_timeout=x |
| 687 | where x is the total number of seconds to wait before timing out.\n""" |
| 688 | warnings.warn(msg, DeprecationWarning) |
| 689 | |
| 690 | if self.read_timeout_override: |
| 691 | read_timeout = self.read_timeout_override |
| 692 | |
| 693 | output = "" |
| 694 | loop_delay = 0.01 |
| 695 | start_time = time.time() |
| 696 | # if read_timeout == 0 or 0.0 keep reading indefinitely |
| 697 | while (time.time() - start_time < read_timeout) or (not read_timeout): |
| 698 | output += self.read_channel() |
| 699 | |
| 700 | if re.search(pattern, output, flags=re_flags): |
| 701 | if "(" in pattern and "(?:" not in pattern: |
| 702 | msg = f""" |
| 703 | Parenthesis found in pattern. |
| 704 | |
| 705 | pattern: {pattern}\n |
| 706 | |
| 707 | This can be problemtic when used in read_until_pattern(). |
| 708 | |
| 709 | You should ensure that you use either non-capture groups i.e. '(?:' or that the |
| 710 | parenthesis completely wrap the pattern '(pattern)'""" |
| 711 | log.debug(msg) |
| 712 | results = re.split(pattern, output, maxsplit=1, flags=re_flags) |
| 713 | |
| 714 | # The string matched by pattern must be retained in the output string. |
| 715 | # re.split will do this if capturing parenthesis are used. |
| 716 | if len(results) == 2: |
| 717 | # no capturing parenthesis, convert and try again. |