JK123
JK123

Reputation: 1

Pexpect - Read from constantly outputting shell

I'm attempting to have pexpect begin running a command which basically continually outputs some information every few milliseconds until cancelled with Ctrl + C.

I've attempted getting pexpect to log to a file, though these outputs are simply ignored and are never logged.

child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')

This results in the command being logged with an empty output.

I have also attempted letting the process run for a few seconds, then sending an interrupt to see if that logs the data, but this again, results in an almost empty log.

child = pexpect.spawn(command)
child.logfile = open('mylogfile.txt', 'w')
time.sleep(5)
child.send('\003')
child.expect('$')

This is the data in question:

image showing the data constantly printing to the terminal

I've attempted the solution described here: Parsing pexpect output though it hasn't worked for me and results in a timeout.

Upvotes: 0

Views: 310

Answers (1)

JK123
JK123

Reputation: 1

Managed to get it working by using Python Subprocess for this, not sure of a way to do it with Pexpect, but this got what I described.

def echo(self, n_lines):
    output = []
    if self.running is False:
        # start shell
        self.current_shell = Popen(cmd, stdout=PIPE, shell=True)
        self.running = True

        i = 0
        # Read the lines from stdout, break after reading the desired amount of lines.
        for line in iter(self.current_shell.stdout.readline, ''):
            output.append(line[0:].decode('utf-8').strip())
            if i == n_lines:
                break
            i += 1
    return output

Upvotes: 0

Related Questions