Python如何从pexpect子级读取输出?

Python如何从pexpect子级读取输出?,python,pexpect,Python,Pexpect,在我的输出中,我从这些代码中得到的只是 child = pexpect.spawn ('/bin/bash') child.sendline('ls') print(child.readline()) print child.before, child.after 但是当我的代码是 ls ls 然后它就可以了,但只适用于前两张照片。我是否使用了错误的send命令?我尝试了发送、写入、发送线路,但再也找不到了 child = pexpect.spawn('ls') print(child.

在我的输出中,我从这些代码中得到的只是

child = pexpect.spawn ('/bin/bash')
child.sendline('ls')
print(child.readline())
print child.before, child.after
但是当我的代码是

ls

ls 
然后它就可以了,但只适用于前两张照片。我是否使用了错误的send命令?我尝试了发送、写入、发送线路,但再也找不到了

child = pexpect.spawn('ls')
print(child.readline())
print child.before, child.after
转到打开您的日志文件:- 到终点站

#!/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(".*\$ ")
依照


在peexpect中,在
expect
方法之后填充
before
after
属性。在这种情况下,最常见的情况是等待提示(这样您就知道前面的命令已经执行完毕)。因此,在您的情况下,代码可能如下所示:

# 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

我认为你所需要的是:

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)

甚至

p = pexpect.spawn('/bin/bash -c "ls"')
p.expect(pexpect.EOF)
print(p.before)
请尝试以下操作:

print(pexpect.run('ls'))
read()
将为您提供ls的全部输出

import pexpect
child = pexpect.spawn('ls')
print child.read() # not readline
请参见从类spawn(SpawnBase)docstring复制,可能示例2就是您想要的

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

import sys
import pexpect
child = pexpect.spawn('ls')
child.logfile = sys.stdout
child.expect(pexpect.EOF)
标准输出的示例日志::

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

在我的测试中也适用于
spawnu
,而其他顶级答案则不适用。可能需要首先验证命令是否已完成,但对于
ls
可能无关紧要。警告:如果
child.sendline(…)
是程序的最后一行,则不会(有时间)捕获输出。期待EOF帮助:
child.expect(pexpect.EOF)
@维克多塞尔吉恩科编辑。谢谢还有几个注意事项:1。我会先分配
logfile
。2.仅当流实际结束时,期望EOF才起作用。如果我们正在生成一个shell,我们必须显式地添加
exit
作为最后一个命令。这里没有生成shell,但这是一个很好的观点。不过,添加了另一个东西。这个例子可以很容易地用于钓鱼…只要在python3中使用sayinopen(“/tmp/mylog”,“wb”),我们就可以得到字节output@Ashwani请参阅这有没有一种方法可以忽略您在打印
child.before
时编写的命令?我想我只是修剪一下直到看到
\r\n
import pexpect
child = pexpect.spawn('ls')
print child.read() # not readline
import sys
import pexpect
child = pexpect.spawn('ls')
child.logfile = sys.stdout
child.expect(pexpect.EOF)
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