【问题标题】:Need little assistance with pexpect interaction在预期交互方面几乎不需要帮助
【发布时间】:2012-07-02 15:13:35
【问题描述】:

使此代码与 pexpect 模块一起工作几乎不需要帮助。

此代码通过登录服务器执行 git pull,然后下载最新代码(如果升级可用)或只是发送一条消息说“已经是最新的”。

代码实际上识别了密码屏幕,但没有识别文本“已经是最新的”

不确定我是否在这里遗漏了什么。

代码中的一个 sn-p 是:

        p = pexpect.spawn('git pull',cwd = comp_dir,maxread = 10000, timeout = 100)
        i = p.expect(['password:','Already up-to-date.',pexpect.EOF])
        if i == 0:
            output_lines = p.before
            output_line_list = output_lines.split('\r\n')
            for line in output_line_list: print line
            count = 0
            p.sendline(pwd)
            while count < 3:  **# The server in case of unsuccessful login asks for password thrice so this check...  (not sure if there is a better way of achieving this)**
                try:
                    output = p.expect('Permission denied')
                    count+=1
                    p.sendline(pwd)
                    p.logfile = sys.stdout
                except:
                    print 'Successful Login !!!! ------'
                    p.expect('Already up-to-date',timeout=None)
                    count = 3
        if i == 1:
            output_lines = p.before
            output_line_list = output_lines.split('\r\n')
            for line in output_line_list: print line
            p.expect(pexpect.EOF)

非常感谢任何帮助。

谢谢, -维杰

【问题讨论】:

    标签: python pexpect


    【解决方案1】:

    这个逻辑好像有点不对。

    起初:你期待一组提示

    i = p.expect(['password:','Already up-to-date.',pexpect.EOF])
    

    当密码提示首先被发送时,它可以正常工作。然后,即使您收到提示 - '已经是最新的。'

    您已更改 pexpect 以检查“密码被拒绝”

    output = p.expect('Permission denied')
    

    我相信任何点都只有一条期望线处于活动状态。此外,您不能在出现提示后设置期望值。

    您必须更改脚本以按顺序检查预期的行

    i = p.expect(['password:','Already up-to-date.','Permission denied', pexpect.EOF])
    if i == 0:
       .... send password
       i = p.expect(['password:','Already up-to-date.','Permission denied', pexpect.EOF])
    if i == 2:
       .... send password
       i = p.expect(['password:','Already up-to-date.','Permission denied', pexpect.EOF])
    if i == 1:
       .... print "already updated"
       i = p.expect(['password:','Already up-to-date.','Permission denied', pexpect.EOF])
    if i == 3:
       .... print output
    

    基本上,您在任何时候都只有一个活动的 expect 命令处于活动状态。如果您期待一行“xyz”并且它收到“123”。它只会超时等待“xyz”。

    【讨论】:

    • 嗨,先生,关于这个逻辑的一个快速问题..当用户输入密码时,它进入条件 i == 2: 并且经过 3 次尝试后它是如何出现的? 3次尝试后会触发EOF吗?我不认为它会触发 EOF,因为我没有看到在条件 i==3 上给出的打印语句
    • @user596922:EOF 应该在提供密码之后出现。您可以尝试使其连续
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2011-01-27
    • 2014-02-06
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多