Method expect of pexpect python module breaks when matching a string in old output

戏子无情 提交于 2020-04-30 07:43:53

问题


I'm trying to work with gdb remotely, using pexpect. This is my current code:

child = pexpect.spawn("ssh root@192.168.3.10 \"gdb\"")
child.logfile = sys.stdout
child.expect("password:")
child.sendline("xxxx")
child.expect("(gdb)")
child.sendline("attach 9813")
child.expect("(gdb)")
child.sendline("info registers")
child.expect("(gdb)")
child.sendcontrol('c')

And this is a part of my console output:

(...)
GNU gdb (GDB) 7.4.1-debian
(...)
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
(gdb) attach 9813
info registers
test@test-virtual-machine:~$

While I expect something like this:

(...)
GNU gdb (GDB) 7.4.1-debian
(...)
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
(gdb) attach 9813
<Attaching...>
(gdb) info registers
<Registers info displayed...>
(gdb) <Ctrl+C is done>
test@test-virtual-machine:~$

So, the problem seems to be that after matching first (gdb) and sending first command attach 9813, pexpect is not expecting a second (gdb) line to send a new command info registers. It sees the first (gdb) again, matches it and just sends a second command without waiting until the first one is executed (until we are attached to a needed proccess).

How can I make it analyse only the following output? Without matching the previous output twice? I saw a sample like this for ftp server:

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')

As I understand, here pexpect manages to react to ftp> in required order and sends commands consecutively. My code seems to be similar.

I also tried flushing stdout, it did not work.


回答1:


GDB seems to sometimes show the prompt again before any output from commands. You are matching the first prompt, sending your command, then immediately matching the 'premature' prompt before the result is displayed. This means that the Control-C at the end is sent before the result from 'info registers' is displayed, but the rest of the script appears to work.

The solution is to match any expected output before sending the next command.




回答2:


I was having the same issue. Joelmatth's answer reminded me of the fix.

trash = child.expect([".+"])

The ".+" matches on the first thing it finds and helps flush everything out.



来源:https://stackoverflow.com/questions/24881362/method-expect-of-pexpect-python-module-breaks-when-matching-a-string-in-old-outp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!