pexpect / ptyprocess

Run a subprocess in a pseudo terminal
https://ptyprocess.readthedocs.io/en/latest/
Other
222 stars 71 forks source link

PtyProcess.read() returns a different value every call #60

Open gggal123 opened 3 years ago

gggal123 commented 3 years ago

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.

takluyver commented 3 years ago

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