問題描述
我創(chuàng)建了一個 Python 腳本,用于監(jiān)視日志文件的更改(如 tail -f)并將其顯示在控制臺上.我想在網(wǎng)絡(luò)瀏覽器中訪問 Python 腳本的輸出.我需要什么來創(chuàng)建這個?我正在考慮使用 Django 和 jQuery.非常感謝任何提示或示例.
I've created a Python script that monitors a logfile for changes (like tail -f) and displays it on a console. I would like to access the output of the Python script in a webbrowser. What would I need to create this? I was thinking about using Django and jQuery. Any tips or examples are greatly appreciated.
推薦答案
首先創(chuàng)建一個python腳本來監(jiān)控日志文件的變化.如果您只需要它來進行調(diào)試 - 測試目的,那么使用 Django 或其他 Web 框架就有點過頭了.使用套接字實現(xiàn) Http Web 服務(wù)器功能非常容易.每當一個 Http GET 請求到來時,只提供來自不同請求的差異.為了實現(xiàn)這一點,您需要在內(nèi)存中存儲每個請求的狀態(tài)(例如文件中最后一行的編號).
First create a python script that monitors the log file for changes. If you only need this for debugging - testing purposes, then it is an overkill to use Django or another web framework. It is very easy to implement Http Web server functionality using sockets. Whenever an Http GET request is coming, serve only the difference from the different request. In order to achieve this you need to store in memory the status of every request coming (e.g.number of last line in the file).
jQuery 部分實際上非常簡單.使用 setTimeout 函數(shù)設(shè)置定時器.這樣的事情會做:
The jQuery part is actually quite easy. Set up a timer with setTimeout function. Something like this will do:
function doUpdate() {
$.ajax({type: "GET", url : tailServiceUrl,
success: function (data) {
if (data.length > 4)
{
// Data are assumed to be in HTML format
// Return something like <p/> in case of no updates
$("#logOutputDiv").append(data);
}
setTimeout("doUpdate()", 2000);
}});
}
setTimeout("doUpdate()", 2000);
您還可以為錯誤和超時創(chuàng)建回調(diào),以報告服務(wù)器問題.
You can also create callbacks for error and timeout to report a problem with the server.
這篇關(guān)于瀏覽器中的tail -f的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!