pexpect/ptyprocess

PtyProcess.read() returns a different value every call

Opened this issue · 1 comments

This is a very severe bug. When calling Ptyprocess.read() the value returned is different almost every time:

ptyprocess.PtyProcess.spawn(['openssl', "ec", '-noout', '-text', '-in', '/opt/key/s128r1.key']).read()

The output:
image

And again with the same params:
image

And again:
image

I don't know what is causing this but this is very weird.

You've got a race condition. The child process is writing data to the pty while the parent process is reading it. How quickly they happen will determine how much data there is for the parent to read.

This is expected behaviour, because the ptyproc.read() doesn't have the common Python convenience feature that calling it with no arguments waits for all the data before returning. It behaves more like the standard C read() function, in that it returns as soon as any data is available.

To read all the output until the child process finishes, you need to do something like this:

ptyproc = ptyprocess.PtyProcess.spawn(['openssl', "ec", '-noout', '-text', '-in', '/opt/key/s128r1.key'])

out = []
while True:
    try:
        out.append(ptyproc.read())
    except EOFError:
        break