【发布时间】:2016-08-12 17:49:23
【问题描述】:
我正在使用以下 Python 代码。代码相当简单,pexpect 将echo testcase 发送到终端,然后监视终端是否出现testcase,然后通过设置bool_value=True 来验证它是否看到了回显(假设它看到了预期的输出)。
#!/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')。 -
我将建议更改为
echo -n。抛出异常的唯一变化是before (last 100 chars): 'testcase\r\n'行变为before (last 100 chars): 'testcase'。通过使用expect('testcase\n')或expect('testcase\r\n')或在代码中添加新的expect('\r\n')行,异常不会改变。
标签: python python-2.7 pexpect