我正在尝试进行冗长的操作但是使用超时参数看起来并没有改变超时异常被触发之前的时间长度。这是我的代码:
child = pexpect.spawn('scp file user@:/temp', timeout=300)
whichMatched = child.expect(['(?i)Password','Are you sure you want to continue connecting (yes/no)?'], timeout=300)
异常显示超时= 30,这是默认值。
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 6222
child_fd: 4
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
答案 0 :(得分:9)
如果您只在.spawn调用中指定超时,则无法覆盖,或者在.expect调用中单独使用timeout = 300,这似乎有效。
答案 1 :(得分:6)
试过以下内容似乎有效:
child.timeout = 300
child.expect( “...”)
答案 2 :(得分:1)
我相信@darricks是不正确的。这是一个示例,显示即使没有为expect()
指定超时,也尊重spawn()
的超时参数。
test_pexpect.py
#! /usr/bin/env python
import pexpect
child = pexpect.spawn('sleep 50')
i = child.expect(['.* password:', 'Are you sure you want to continue connecting'], timeout=40)
这里是Linux的输出。 test_pexpect.py
的输出列出“超时:30”。这只是显示spawn()
的超时。但是底部time
的输出显示脚本在40秒时终止。因此expect()
超时受到尊重。
$ time test_pexpect.py
Traceback (most recent call last):
File "./test_pexpect.py", line 5, in <module>
i = child.expect(['.* password:', 'Are you sure you want to continue connecting'], timeout=40)
File "/usr/rx30/musl/Python-2.7.14.install/lib/python2.7/site-packages/pexpect/spawnbase.py", line 341, in expect
timeout, searchwindowsize, async_)
File "/usr/rx30/musl/Python-2.7.14.install/lib/python2.7/site-packages/pexpect/spawnbase.py", line 369, in expect_list
return exp.expect_loop(timeout)
File "/usr/rx30/musl/Python-2.7.14.install/lib/python2.7/site-packages/pexpect/expect.py", line 119, in expect_loop
return self.timeout(e)
File "/usr/rx30/musl/Python-2.7.14.install/lib/python2.7/site-packages/pexpect/expect.py", line 82, in timeout
raise TIMEOUT(msg)
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0xf76b30ac>
command: /bin/sleep
args: ['/bin/sleep', '50']
buffer (last 100 chars): ''
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 31968
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
0: re.compile('.* password:')
1: re.compile('Are you sure you want to continue connecting')
real 0m40.235s
user 0m0.053s
sys 0m0.043s
$