python3 pexpect spawn对象行引用被跳过



Python版本:3.8.0pexpect Version: 4.8.0

def runCmd( self, cmd, thisTimeout = None ):
output = ""
if not thisTimeout:
thisTimeout = self.conn.timeout
try:
print("debug: %s" % cmd)
self.conn.sendline(cmd)
print( "before: %s " % self.conn.before.decode() )
index = self.conn.expect( self.expList, timeout = thisTimeout )
output += self.conn.before.decode()
print( "after: %s " % self.conn.after.decode() )
print( "before after: %s" % self.conn.before.decode() )
except Exception as e:
#expect exception thrown
print( "Error running command %s" % cmd )
print( e )
output = "Error: %s" % str(self.conn)
print("yo man %s" % self.conn.before.decode() )
output = output.replace(cmd, "").strip()
print("this has to print %s " % output)
return output

该函数通过pexpect接口执行cmd并返回输出。

运行的Python/pexpect版本:Python版本:3.6.9Pexpect version: 4.2.1

更新python脚本以在python 3.8.0/pexpect 4.8.0上运行后,发送给pexpect的第一个命令有时返回空输出。原因是当变量self.conn.before.decode()被引用时,python代码不会被执行或无效。

所描述情况的示例输出:

debug: cat /etc/hostname
before:  
after: ubuntu@ip-172-31-1-219:~$ 

this has to print  

期望行为:

debug: cat /etc/hostname

after: ubuntu@ip-172-31-1-219:~$ 
before after:  cat /etc/hostname
ip-172-31-1-219
yo man  cat /etc/hostname
ip-172-31-1-219
this has to print ip-172-31-1-219

但是这一次,在:之前的行被跳过。这是怎么回事?!降级是不可能的,因为async(pexpect(<=4.2.1)使用async作为函数/变量签名)成为关键字。

更新:这些行被执行了,但是在我把它作为字节串打印出来之后,它就打印出来了。

before after: b' rx1b[Kx1b]0;ubuntu@ip-172-31-1-219: ~x07'

正确输出的是

before after: b' cat /etc/hostnamernip-172-31-1-219
rnx1b]0;ubuntu@ip-172-31-1-219: ~x07'

跳过beforebefore after行的原因是它们包含回车字符r和转义序列x1b[K

回车符用于将光标移动到行首。如果在要写入的字符串中,它后面有字符,则从光标位置开始打印它们,取代现有的打印字符。

ANSI控制序列x1b[K擦除从光标位置到行尾的行。这将清除特定情况下已经打印的字符串。

最新更新