提前感谢您的帮助。我对Python不太熟悉,对HTML更是新手。
最近几天,我一直在尝试创建一个网页,其中包含按钮,可以在家庭服务器上执行任务。
目前,我有一个生成带有按钮的页面的Python脚本:
(See the simplified example below. removed code to clean up post)
然后是一个运行该命令并将输出显示在页面上的Python脚本:
iframe
。(See the simplified example below. removed code to clean up post)
这将在命令完成后输出整个完成的输出。我还尝试添加
-u
选项到Python脚本中以无缓冲方式运行它。我还尝试使用Python subprocess
。如果有帮助,我正在运行的命令类型是apt-get update
和其他用于移动文件和修复文件夹权限的Python脚本。当从普通Ubuntu服务器终端运行时,它可以正常运行并实时输出,从我的研究来看,它应该在命令运行时输出。
有人能告诉我哪里出了问题吗?我应该使用不同的语言执行此功能吗?
编辑简化示例:
初始页面:
#runcmd.html
<head>
<title>Admin Tasks</title>
</head>
<center>
<iframe src="/scripts/python/test/createbutton.py" width="650" height="800" frameborder="0" ALLOWTRANSPARENCY="true"></iframe>
<iframe width="650" height="800" frameborder="0" ALLOWTRANSPARENCY="true" name="display"></iframe>
</center>
创建按钮的脚本:
cmd_page = '<form action="/scripts/python/test/runcmd.py" method="post" target="display" >' + '<label for="run_update">run updates</label><br>' + '<input align="Left" type="submit" value="runupdate" name="update" title="run_update">' + "</form><br>" + "\n"
print ("Content-type: text/html")
print ''
print cmd_page
应该运行命令的脚本:
# runcmd.py:
import os
import pexpect
import cgi
import cgitb
import sys
cgitb.enable()
fs = cgi.FieldStorage()
sc_command = fs.getvalue("update")
if sc_command == "runupdate":
cmd = "/usr/bin/sudo apt-get update"
pd = pexpect.spawn(cmd, timeout=None, logfile=sys.stdout)
print ("Content-type: text/html")
print ''
print "<pre>"
line = pd.readline()
while line:
line = pd.readline()
我还没有测试上述简化的例子,所以不确定其是否可用。
编辑:
简化的例子现在应该可以工作了。
编辑:
Imrans下面的代码,如果我打开一个浏览器到ip:8000,它会显示输出,就像在终端中运行一样,这正是我想要的。但是我正在使用Apache服务器作为我的网站和一个iframe来显示输出。我该怎么做?
编辑:
现在我已经使用Imrans下面的例子将输出传送到iframe,但它似乎仍然缓冲,例如:
If I have it (the script through the web server using curl ip:8000) run apt-get update in terminal it runs fine but when outputting to the web page it seems to buffer a couple of lines => output => buffer => ouput till the command is done.
But running other python scripts the same way buffer then output everything at once even with the -u flag. While again in terminal running curl ip:800 outputs like normal.
这是否就是它应该工作的方式?
编辑 2014年3月19日:
使用Imrans的方法运行的任何bash / shell命令似乎都可以实时输出到iframe中。但如果我通过它运行任何类型的python脚本,则输出会被缓冲,然后发送到iframe。
我可能需要将由运行Web服务器的脚本运行的python脚本的输出PIPE到iframe吗?