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次打印。我使用错误的发送命令吗?我尝试了发送,写入,发送,并且找不到了。
答案 0 :(得分:16)
在pexpect中,在before
方法之后填充after
和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)
答案 1 :(得分:10)
尝试以下方法:
import pexpect
child = pexpect.spawn('ls')
print child.read() # not readline
read()
将为您提供ls的整个输出。
答案 2 :(得分:9)
#!/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
答案 3 :(得分:3)
我认为你所需要的只是:
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'))
答案 4 :(得分:3)
import sys
import pexpect
child = pexpect.spawn('ls')
child.logfile = sys.stdout
child.expect(pexpect.EOF)
答案 5 :(得分:1)
从类spawn(SpawnBase)docstring复制,也许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