捕捉即将死去的过程 [英] Catching a dying process in pexpect

查看:72
本文介绍了捕捉即将死去的过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些pexpect的东西,这些东西基本上是通过telnet发送命令的.

I'm writing some pexpect stuff that's basically sending commands over telnet.

但是,我的telnet会话可能会死掉(由于网络问题,电缆被拔掉了等等).

But, it's possible that my telnet session could die (due to networking problems, a cable getting pulled, whatnot).

我该如何初始化telnet会话,以便如果它死了,我可以捕获它并告诉它重新连接,然后继续执行它所在的代码.

How do I initialize a telnet session such that, if it dies, I can catch it and tell it to reconnect and then continue execution of the code where it was at.

这可能吗?

推荐答案

恕我直言,通常使用诸如 telnetlib ,但pexpect中的有效咒语是:

IMHO, you're normally better-off with a currently-maintained library like exscript or telnetlib, but the efficient incantation in pexpect is:

import pexpect as px

cmds = ['cmd1', 'cmd2', 'cmd3']
retcode = -1
while (retcode<10):
    if (retcode<2):
        child = px.spawn('telnet %s %s' % (ip_addr,port))
    lregex = '(sername:)'            # Insert regex for login prompt here
    pregex = '(prompt1>)|(prompt2$)' # Insert your prompt regex here
    # retcode = 0 for px.TIMEOUT, 1 for px.EOF, 2 for lregex match...
    retcode = child.expect([px.TIMEOUT, px.EOF, lregex, pregex],timeout = 10)
    if (retcode==2):
        do_login(child)  # Build a do_login() method to send user / passwd
    elif (2<retcode<10) and (len(cmds)>0):
        cmd = cmds.pop(0)
        child.sendline(cmd)
    else:
        retcode = 10

这篇关于捕捉即将死去的过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆