gpt4 book ai didi

python - print 和 pexpect 记录并读取文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:58 25 4
gpt4 key购买 nike

我实际上正在尝试将命令及其输出写入文件,然后读取该文件。文件已创建,但在读取文件时,它会给出 valueerror i/o 操作错误。我在这里缺少什么。 ?

import pexpect
import time,sys
from StringIO import StringIO

telconn=pexpect.spawn('telnet 10.24.12.109')
telconn.logfile = sys.stdout
telconn.expect(":")
telconn.send("user" + "\r")
telconn.expect(":")
telconn.send("pass" + "\r\r\r\r\n\n\n")
telconn.expect("key to proceed.")
telconn.send ("\003")
telconn.expect("root>")
sys.stdout=open("test1.txt","w")

print "Telnet connection is done"

telconn.sendline('ls -al');
telconn.expect (['root>',pexpect.EOF])
ls = telconn.before

telconn.sendline('pwd');
telconn.expect (['root>',pexpect.EOF])
pwd = telconn.before

telconn.sendline('cli');
telconn.expect (['#',pexpect.EOF])
cli = telconn.before

telconn.sendline('\n\n');

telconn .sendline('exit');
telconn.close()

print ls
print pwd
print cli
print "Ended session"

sys.stdout.close()

sys.stdout = open("test1.txt", "r+")
str = sys.stdout.read();
print "Read String is : ", str
# Close opend file

print "Read String is : ", str
sys.stdout.close()

最佳答案

编辑(OP希望系统调用打印到文件):

将标准输出保存到某个临时变量,因此只需添加:

prev_std = sys.stdout

在执行之前sys.stdout=open("test1.txt","w")

完成并关闭 sys.stdout 后,恢复原来的:

sys.stdout = prev_std

关于python - print 和 pexpect 记录并读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com