我正在處理以下一段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')'行,異常是不變的。 –