我实际上是在尝试将命令及其输出写入文件然后读取文件。该文件已创建,但是为了读取该文件,它会在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()
答案 0 :(得分:1)
编辑(OP希望系统调用打印到文件):
将标准输出保存到某个temp var,所以只需添加:
prev_std = sys.stdout
之前sys.stdout=open("test1.txt","w")
。
完成并关闭sys.stdout
后,恢复原来的一个:
sys.stdout = prev_std