所以我使用 Django 框架将控制台输出显示到 HTML。要执行命令,我使用 check_output
的 subprocess
Python 中的模块。它接收来自 HTML 输入表单的输入。问题是我在 HTML 页面上只看到“None
”,这是 output
的默认值在 views
文件。
下面是 View 文件和 HTML 文件的代码。我是这方面的新手,所以我很感激你的帮助。
View .py
from django.shortcuts import render
from django.shortcuts import redirect
from .forms import command_form
import subprocess as sp
# Create your views here.
def welcome_page(request):
output=""
if request.method == "POST":
myform = command_form(request.POST)
if (myform.is_valid()):
execute_command = myform.cleaned_data['cmd_string']
output = sp.check_output(execute_command, shell=True)
else:
myform = command_form()
return render(request, 'ovs/welcome.html', {'output': output})
else:
return render(request, 'ovs/welcome.html', {})
欢迎.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welcome to ovs GUI</title>
</head>
<body>
<h3>Choose the option:</h3>
<form method="POST">{% csrf_token %}
Enter the command: <input type="text" name="cmd_string" id="cmd_string"/>
<input type="submit" value="Run"/>
</form>
<h3>{{ output }}</h3>
</body>
</html>
表格
from django import forms
class command_form(forms.Form):
command = forms.CharField(max_length=200)
最佳答案
您没有将表单域正确地呈现为 HTML。您创建了 command_form
形式,你永远不会利用它。但是,您应该为 python class
使用驼峰式名称。 es,像这样 CommandForm
.
在您的 HTML 中,编写以下代码:
<form method="POST">{% csrf_token %}
Enter the command: {{ myform }}
<input type="submit" name="submit_cmd" value="Run" />
</form>
{% if output %}<h3>{{ output }}</h3>{% endif %}
{% if exit_code %}<h3>Your command returned an error: {{ error_msg }}</h3>{% endif %}
{{ my_form }}
将自动扩展为 <input type="text" ...>
现在,写下你的
welcome_page
像这样查看:def welcome_page(request):
output = ""
# Initialize the form. At this point you have an unbound/invalid form
myform = command_form() # better write it as CommandForm
if request.method == "POST":
myform = command_form(request.POST)
if myform.is_valid():
# execute_command variable, should now contain the command typed by the user in the text box
execute_command = myform.cleaned_data['command']
try:
# If the return code is non-zero, CalledProcessError will be raised
output = sp.check_output(execute_command, shell=True)
except sp.CalledProcessError:
exit_code, error_msg = output.returncode, output.output
else:
# Do something when the form is not valid. Maybe add a message or something, or not implement else clause at all.
return render(request, 'ovs/welcome.html', locals())
警告!根据 docs说:
Using
shell=True
can be a security hazard.
关于python - 如何在 Django 中将控制台输出显示为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992963/