在 IronPython for ASP.NET 中改写 print 以方便调试

python 语言中最方便的莫过于 print 语句,搭配 dir() 等函数,能随时查看对象的属性,内容等。而 IronPython for ASP.NET 的环境下 print 是不会显示出来的。用下面的办法,可以改写输出流到 web 页面上。

先在 App_Script 目录下建立一个 debug.py,内容如下:

#coding:utf-8

import sys
from System.Web import HttpContext

class Log(object):
    
def __init__(self):
        self.response 
= HttpContext.Current.Response
    
    
def write(self, data):
        self.response.Write(data)
        
def start_debug():
    sys.stdout 
= Log()
        
if __name__ == '__main__':
    start_debug()
    
print "test"
    

这样就把输出流重定向到了 Response.Write 上。
在具体页面中,这样调用:

import debug
debug.start_debug()
print '测试输出'

输出结果会在网页上显示出来。

原文地址:https://www.cnblogs.com/RChen/p/ipy_aspnet_print.html