2011-08-01 32 views
0

我正在使用金字塔,我知道這可能不是首選的方式,但它會很酷。我有一堆打印到stdout的Python腳本。現在我想將這些腳本作爲金字塔中的請求/響應的一部分來運行。我的意思是我想捕獲腳本的stdout並將其寫入模板。使用變色龍ZPT模板寫出打印語句

的捕獲標準輸出部分非常簡單:

import sys 
sys.stdout = tbd 

至於我可以看到選擇render_to_response不支持任何這樣:

return render_to_response(’templates/foo.pt’, 
    {’foo’:1, ’bar’:2}, 
    request=request) 

任何想法,我怎樣才能得到一個寫()在模板上操作?

回答

3

我可能會使用的子模塊捕獲腳本的標準輸出,而不是將其導入,直接運行它:

import StringIO 
output = StringIO.StringIO() 
result = subprocess.call('python', 'myscript.py', stdout=output) 
value = output.get_value() 

string = render(’templates/foo.pt’, 
    {'value':value}, 
    request=request) 
3

你可以通過一個StringIO.StringIO對象到stdout,那麼還可通過上下文字典把它傳遞給模板,只是在模板調用StringIO.StringIO.getvalue()在適當的時間:

import sys 

def my_view(request): 
    old_stdout = sys.stdout 
    new_stdout = StringIO.StringIO() 
    sys.stdout = new_stdout 

    # execute your scripts 

    sys.stdout = old_stdout 

    return render_to_response('template/foo.pt', {'foo': 1, 'bar': 2, 'stdout': new_stdout}, 
     request=request) 

,然後在模板:

<html> 
    <body> 
    <!-- stuff --> 
    ${stdout.getvalue()} 
    <!-- other stuff --> 
    </body> 
</html> 

你可能需要添加一個過濾器,確保文本格式正確,或者你可能只是創建StringIO.StringIO的子類與__html__方法會使你認爲合適的東西。

+0

的作品就像一個魅力。非常感謝! – mark