pexpect前面运行了一些命令,继续运行命令时,expect会从上一次运行expect后的所有输出中查找符合规则的字符,是否有办法晴空之前命令的输出
时间: 2024-02-24 11:54:30 浏览: 11
是的,有办法清空之前命令的输出。您可以在运行命令之前使用 `clear()` 方法清空之前命令的输出。例如:
```python
import pexpect
child = pexpect.spawn('ls -l')
child.expect(pexpect.EOF)
print(child.before)
# 清空之前命令的输出
child.clear()
child.sendline('echo "Hello World!"')
child.expect(pexpect.EOF)
print(child.before)
```
在上面的代码中,我们使用 `clear()` 方法清空了之前 `ls -l` 命令的输出。然后我们发送了一个新的命令 `echo "Hello World!"`,并且得到了正确的输出。注意,`clear()` 方法只清空了 pexpect 对象的内部缓冲区,而不会清空终端屏幕上的输出。
相关问题
python中如何实现expect效果
在 Python 中,可以使用 `pexpect` 模块来实现类似于 expect 的功能。`pexpect` 是一个 Python 模块,用于控制和自动化其他程序和终端应用程序的交互。下面是一个简单的示例:
```python
import pexpect
child = pexpect.spawn('ssh user@host') # 启动一个 ssh 进程
child.expect('password:') # 等待输入密码
child.sendline('mypassword') # 发送密码
```
在上面的示例中,`spawn()` 函数启动了一个 ssh 进程,并返回一个 `pexpect.spawn` 对象。然后,使用 `expect()` 方法等待 ssh 进程输出字符串 "password:",一旦出现该字符串,`expect()` 方法将返回,并可以使用 `sendline()` 方法发送密码字符串 "mypassword"。
除了 ssh,`pexpect` 还可以用于处理 telnet、ftp、scp、sftp、su、passwd 等其他交互式命令行工具和脚本。
python中scp命令使用
在Python中使用scp命令可以通过expect模块来实现。具体步骤如下:
1. 首先需要在操作系统中安装expect。
2. 在Python脚本中导入expect模块。
3. 使用spawn函数来执行scp命令,其中包括端口号、本地源文件、用户名、主机名和远程目标文件等参数。
4. 使用sendline函数来输入密码。
5. 使用expect函数来等待scp命令执行完成。
下面是一个使用expect模块实现scp命令的Python脚本范例:
```python
#!/usr/bin/python
#coding:utf-8
import sys,re
import os
import subprocess
import pexpect
#scp file to remote node.
def scpFileToRemoteNode(user,ip,port,passwd,localsource,remotedest):
child = pexpect.spawn('scp -P %s -r %s %s@%s:%s'%(port,localsource,user,ip,remotedest))
try:
i = child.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
child.sendline(passwd)
elif i == 1:
child.sendline('yes\n')
child.expect('password: ')
child.sendline(passwd)
child.expect(pexpect.EOF)
print child.before
except pexpect.ExceptionPexpect, e:
print str(e)
#调用函数
scpFileToRemoteNode('username','192.168.1.1','22','password','/home/localfile','/home/remotefile')
```