简体   繁体   中英

Why Python pexpect does not match the expected prompt with newline here

I am trying to execute client.py from run.py. The client.py prompts for an input. I have written a simple pexpect code but it doesn't match the prompt and hangs.

Here is my code

client.py

input = raw_input("Please data, default [ /Anything ]:\n")
if input == "Admin":
    print "Welcome Admin"
else:
    print "Welcom Guest"

run.py

import pexpect
child = pexpect.spawn ('python client.py')
child.expect('Please data, default [ /Anything ]:\n')
child.sendline ('anonymous')

Here is an another try with expect_exact, it did not help me..

run1.py

import pexpect
child = pexpect.spawn ('python client.py')
child.expect_exact('Please data, default [ /Anything ]:\n')
child.sendline ('anonymous')

Python and pexpect versions -

Python 2.7.2 (default, May 13 2014, 12:53:14)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pexpect
>>> pexpect.__version__
'3.2'
>>>

您可能希望使用expect_exact而不是expect ,因为后面的方法需要一个正则表达式,其中[是一个特殊字符。

The problem is your \\n character. As explained here . You are sending a \\n but pexpect sees that as a \\r\\n , so you have to tell run.py to expect \\r\\n instead of just \\n :

import pexpect
child = pexpect.spawn ('python client.py')
child.expect_exact('Please data, default [ /Anything ]:\r\n')
child.sendline ('anonymous')

Leave the client.py just as it is (do not add \\r to the raw_input string there).

你可以在Anything方面做一些Anything ,然后继续你的代码。

child.pexpect('Anything')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM