8

我正在尝试进行冗长的操作,但使用 timeout 参数的 pexpect 似乎并没有改变触发超时异常之前的时间长度。这是我的代码:

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)

异常显示 timeout=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
4

3 回答 3

7

如果您仅在 .spawn 调用中指定超时,则它似乎有效,您不能覆盖或在 .expect 调用中单独使用 timeout=300 。

于 2010-07-27T16:48:03.720 回答
6

刚刚尝试了以下,它似乎工作:

child.timeout=300
child.expect("...")

于 2013-08-09T18:01:49.537 回答
2

我相信@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
$
于 2020-07-16T14:11:08.837 回答