29
child = pexpect.spawn ('/bin/bash')
child.sendline('ls')
print(child.readline())
print child.before, child.after

我在输出中得到的所有代码是

ls

ls 

但是当我的代码是

child = pexpect.spawn('ls')
print(child.readline())
print child.before, child.after

然后它可以工作,但仅适用于前 2 次打印。我使用了错误的发送命令吗?我尝试了发送、写入、发送,但再也找不到了。

4

6 回答 6

21

在 pexpectbeforeafter属性是在expect方法之后填充的。在这种情况下最常用的方法是等待提示(这样您就会知道上一个命令已完成执行)。因此,在您的情况下,代码可能如下所示:

child = pexpect.spawn ('/bin/bash')
child.expect("Your bash prompt here")
child.sendline('ls')
#If you are using pxssh you can use this
#child.prompt()
child.expect("Your bash prompt here")
print(child.before)
于 2013-07-16T07:52:06.297 回答
19

尝试以下操作:

import pexpect
child = pexpect.spawn('ls')
print child.read() # not readline

read()将为您提供 ls 的全部输出。

于 2015-09-18T00:25:35.640 回答
13
#!/usr/bin/env python

import pexpect
child = pexpect.spawn("ssh root@172.16.0.120c -p 2222")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("XXXXXXX\r")
child.expect(".*\$ ")
child.sendline("ls\r")
child.expect(".*\$ ")

去打开你的日志文件: - 去终端

$gedit /tmp/mylog

根据https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class

# In Python 3, we'll use the ``encoding`` argument to decode data
# from the subprocess and handle it as unicode:
 child = pexpect.spawn('some_command', encoding='utf-8')
 child.logfile = sys.stdout
于 2013-07-15T07:30:12.800 回答
6

我想你需要的只是:

p = pexpect.spawn('ls')
p.expect(pexpect.EOF)
print(p.before)

或者

p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print(p.before)

或者

p = pexpect.spawn('/bin/bash -c "ls"')
p.expect(pexpect.EOF)
print(p.before)

甚至

print(pexpect.run('ls'))
于 2014-04-28T21:27:08.927 回答
4
import sys
import pexpect
child = pexpect.spawn('ls')
child.logfile = sys.stdout
child.expect(pexpect.EOF)

请参阅有关该主题的手册条目。

于 2015-11-10T22:25:56.057 回答
1

从类 spawn(SpawnBase) 文档字符串中复制,也许 example-2 是你想要的。

示例日志输入和输出到文件::

child = pexpect.spawn('some_command')
fout = open('mylog.txt','wb')
child.logfile = fout

示例日志到标准输出::

# In Python 2:
child = pexpect.spawn('some_command')
child.logfile = sys.stdout

# In Python 3, we'll use the ``encoding`` argument to decode data
# from the subprocess and handle it as unicode:
child = pexpect.spawn('some_command', encoding='utf-8')
child.logfile = sys.stdout
于 2019-01-10T09:31:12.900 回答