我正在处理以下一段Python代码。代码非常简单,pexpect将echo testcase
发送到终端,然后监视终端以查看testcase
的后续出现,然后通过设置bool_value=True
(假设它看到预期的输出)来验证它是否看到了回显。Python pexpect:var.expect('string')'string'未找到时不返回期望值
#!/usr/bin/python
import pexpect
print('Testing case where pexpect finds the expected value: ')
testcase = pexpect.spawn('echo testcase')
bool_value = not testcase.expect('testcase')
print bool_value
testcase.close()
print('Testing case where pexpect does not find the expected value: ')
testcase = pexpect.spawn('echo testcase')
bool_value = not testcase.expect('someothervalue')
print bool_value
testcase.close()
我有什么期望看到的是,第一个测试用例后,bool_value将打印True
。在这种情况下,它只会在添加设置为bool_value = not testcase.expect('testcase')
的奇怪黑客之后(将其设置为expect()返回的逆函数)。
在第二个测试案例中,testcase.expect()
未看到预期值someothervalue
,所以我预计它会返回false
。相反,它会返回一个异常:
Traceback (most recent call last):
File "./echotest.py", line 12, in <module>
bool_value = not testcase.expect('someothervalue')
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1418, in expect
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1433, in expect_list
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1521, in expect_loop
raise EOF(str(err) + '\n' + str(self))
pexpect.EOF: End Of File (EOF). Exception style platform.
<pexpect.spawn object at 0x7f7667a9db10>
version: 3.1
command: /bin/echo
args: ['/bin/echo', 'testcase']
searcher: <pexpect.searcher_re object at 0x7f7667a9d790>
buffer (last 100 chars): ''
before (last 100 chars): 'testcase\r\n'
after: <class 'pexpect.EOF'>
match: None
match_index: None
exitstatus: 0
flag_eof: True
pid: 4619
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
我真的不确定如何根据文档告诉我的情况来纠正此问题。按this previous implementation添加testcase.expect(pexpect.EOF())
返回相同的错误。
如何正确实现此功能?
也许是因为'echo'默认添加了一个换行符?尝试使用'echo -n'或使用'expect('testcase \ n')'。 – Bakuriu
我对'echo -n'进行了建议的修改。抛出异常的唯一变化是'before(last 100 chars):'testcase \ r \ n''变成'before(last 100 chars)':'testcase''。通过在代码中使用expect('testcase \ n')'或expect('testcase \ r \ n')'或添加一个新的'expect('\ r \ n')'行,异常是不变的。 –