| 1495 | |
| 1496 | |
| 1497 | def run_follow(command, cwd=None, fh=sys.stdout, tee=False, live=False, shell=None, capture_output=False): |
| 1498 | doShell = '&&' in command or '&' in command or shell is not None |
| 1499 | if not doShell and not isinstance(command, list): |
| 1500 | command = shlex.split(command) |
| 1501 | process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, |
| 1502 | universal_newlines=True, bufsize=0, close_fds=True, shell=doShell) |
| 1503 | lines_written = 0 |
| 1504 | |
| 1505 | fl = fcntl.fcntl(process.stdout, fcntl.F_GETFL) |
| 1506 | fcntl.fcntl(process.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) |
| 1507 | |
| 1508 | flerr = fcntl.fcntl(process.stderr, fcntl.F_GETFL) |
| 1509 | fcntl.fcntl(process.stderr, fcntl.F_SETFL, flerr | os.O_NONBLOCK) |
| 1510 | |
| 1511 | endstdout = endstderr = False |
| 1512 | errlines = [] |
| 1513 | captured_lines = [] if capture_output else None |
| 1514 | while not (endstderr and endstdout): |
| 1515 | lines_before = lines_written |
| 1516 | if not endstdout: |
| 1517 | try: |
| 1518 | if live: |
| 1519 | chars = process.stdout.read() |
| 1520 | if chars == '' and process.poll() is not None: |
| 1521 | endstdout = True |
| 1522 | else: |
| 1523 | fh.write(chars) |
| 1524 | fh.flush() |
| 1525 | if capture_output: |
| 1526 | captured_lines.append(chars) |
| 1527 | if '\n' in chars: |
| 1528 | lines_written += 1 |
| 1529 | else: |
| 1530 | line = process.stdout.readline() |
| 1531 | if line == '' and process.poll() is not None: |
| 1532 | endstdout = True |
| 1533 | else: |
| 1534 | fh.write("%s\n" % line.rstrip()) |
| 1535 | fh.flush() |
| 1536 | if capture_output: |
| 1537 | captured_lines.append(line) |
| 1538 | lines_written += 1 |
| 1539 | print_line_cr(line, lines_written, stdout=(fh == sys.stdout), tee=tee) |
| 1540 | |
| 1541 | except Exception: |
| 1542 | pass |
| 1543 | if not endstderr: |
| 1544 | try: |
| 1545 | if live: |
| 1546 | chars = process.stderr.read() |
| 1547 | if chars == '' and process.poll() is not None: |
| 1548 | endstderr = True |
| 1549 | else: |
| 1550 | fh.write(chars) |
| 1551 | fh.flush() |
| 1552 | if '\n' in chars: |
| 1553 | lines_written += 1 |
| 1554 | else: |