很多python现有的代码,都是通过print之类的方法,把结果输出到控制台,如下图,当在程序中执行了
print("第一行结果")
print("第二行结果")
print("第三行结果")
后,将会在控制台输出
由于pythonstudio做的程序中无法将这些内容展示出来,所以,可以通过重定向控制台内容的方法来完成,效果如下图
当执行了print语句后,内容输出到MEMO控件中。为简便说明用法,以下做了个简单示例。
界面设计
在窗口中建立一个TButton和一个TMemo控件,分别命名为BtnPrint和MemoCon
其中,Memocon是用来模拟控制台的,BtnPrint是模拟输出内容的
建立重定向类
注意
- 需要引入sys包
- 需要用cls_ref来确认引用的类,如,此处为MemoCon.Lines
# 重定向类
import sys
class reStdOut():
def __init__(self,cls_ref=None):
# 重定向输出到本类
sys.stdout=self
sys.stderr=self
# 内容保存的位置
self.strTest=""
# 引用的类
self.cls_ref=cls_ref
# 重写write方法
def write(self,info):
# 取得内容
self.strTest=info
if self.cls_ref!=None:
# 写回到Memo控件中
self.cls_ref.Text+=info
使用
在窗口文件初始化时,将重定向类实例化
# 创建类,重定向输出,并传递当前类到重定向类
self.NewConsole=reStdOut(cls_ref=self.MemoCon.Lines)
完整代码
import os
from glcl import *
# 引入sys
import sys
class Form1(Form):
def __init__(self, owner):
self.BtnPrint = Button(self)
self.MemoCon = Memo(self)
self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Unit1.pydfm"))
self.BtnPrint.OnClick = self.BtnPrintClick
# 清空Memo组件内容
self.MemoCon.Text=""
# 创建类,重定向输出,并传递当前类到重定向类
self.NewConsole=reStdOut(cls_ref=self.MemoCon.Lines)
# 测试数据
def BtnPrintClick(self, Sender):
print("第一行结果")
print("第二行结果")
print("第三行结果")
# 重定向类
class reStdOut():
def __init__(self,cls_ref=None):
# 重定向输出到本类
sys.stdout=self
sys.stderr=self
# 内容保存的位置
self.strTest=""
# 引用的位置
self.cls_ref=cls_ref
# 重写write方法
def write(self,info):
# 取得内容
self.strTest=info
if self.cls_ref!=None:
# 写回到Memo控件中
self.cls_ref.Text+=info