是否可以让pexpect输出与之匹配的文本?

问题描述

我熟悉Expect脚本,因此当我第一次使用pexpect时,我感到有些奇怪。以这个简单的脚本为例,

from docx import Document

document = Document()
paragraph = document.add_paragraph()

# and now set the paragraph layout to two columns
...

运行时,我将得到以下输出。感觉很自然,因为那是我运行这些命令的方式

#!/usr/bin/expect
set timeout 10
spawn npm login
expect "Username:"
send "qiulang2000\r"
expect "Password:"
send "xxxxx\r"
expect "Email:"
send "qiulang@gmail.com\r"
expect "Logged in as"
interact

但是当我使用pexpect时,无论我如何添加spawn npm login Username: qiulang2000 Password: Email: (this IS public) qiulang@gmail.com Logged in as qiulang2000 on https://registry.npmjs.com/. print(child.after),我都无法获得期望的输出,例如当我运行以下命令时,

print(child.before)

我得到了这些输出,感觉不自然,因为那不是我在运行这些命令时看到的。

#! /usr/bin/env python3
import pexpect
child = pexpect.spawn('npm login')
child.timeout = 10
child.expect('Username:')
print(child.after.decode("utf-8"))
child.sendline('qiulang2000')
child.expect('Password:')
child.sendline('xxxx')
child.expect('Email:')
child.sendline('qiulang@gmail.com')
child.expect('Logged in as')
print(child.before.decode("utf-8"))
child.interact()

那么有可能实现期望的脚本输出吗?

-更新---

有了我从@pynexj得到的评论,我终于使它生效,请在下面检查我的答案。

解决方法

有了评论,我终于使它生效了

#! /usr/bin/env python3

import pexpect
import sys
print('npm login',timeout = 10)
child = pexpect.spawn('npm login')
child.logfile_read = sys.stdout.buffer // use sys.stdout.buffer for python3
child.expect('Username:')
child.sendline('qiulang2000')
child.expect('Password:')
child.sendline('xxxx')
child.expect('Email:')
child.sendline('qiulang@gmail.com')
child.expect('Logged in as')

如果我需要调用child.interact(),那么在它之前调用child.logfile_read = None是很重要的,否则sys.stdout将回显我键入的所有内容。

这里的答案How to see the output in pexpect?说我需要传递python3的编码,但是我发现如果我使用encoding='utf-8'会导致TypeError: a bytes-like object is required,not 'str'如果我根本不设置编码,一切正常。

所以一个简单的ssh登录脚本看起来像这样

#!/usr/bin/env python3

import pexpect
import sys
child = pexpect.spawn('ssh qiulang@10.0.0.32')
child.logfile_read = sys.stdout.buffer
child.expect('password:')
child.sendline('xxxx')
#child.expect('Last login')  don't do that
child.logfile_read = None # important !!!
child.interact()

一个问题仍然没有解决,我在发送密码后添加了一个最后的期望调用以匹配ssh登录输出,例如child.expect('上次登录')

但是,如果我添加了该行,则该行将显示两次。我放弃了尝试,就像一条评论说“ pexpect的行为有点违反直觉”。

Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-141-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

33 packages can be updated.
0 updates are security updates.

Last login: Fri Sep 11 11:44:19 2020 from 10.0.0.132
: Fri Sep 11 11:44:19 2020 from 10.0.0.132

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...