要在Django网页上查看Python脚本的结果,你需要将Python脚本集成到Django视图中,并通过模板将结果显示在网页上。以下是实现这一功能的基本步骤:
# views.py
from django.shortcuts import render
import subprocess
def script_result(request):
# 执行Python脚本并捕获输出
result = subprocess.run(['python', 'path_to_your_script.py'], capture_output=True, text=True)
output = result.stdout
# 将输出传递给模板
context = {'output': output}
return render(request, 'script_result.html', context)
# urls.py
from django.urls import path
from .views import script_result
urlpatterns = [
path('script-result/', script_result, name='script_result'),
]
<!-- templates/script_result.html -->
<!DOCTYPE html>
<html>
<head>
<title>Script Result</title>
</head>
<body>
<h1>Python Script Output</h1>
<pre>{{ output }}</pre>
</body>
</html>
通过以上步骤,你可以在Django网页上查看Python脚本的输出。如果遇到具体问题,可以根据错误信息进行调试或搜索相关解决方案。
领取专属 10元无门槛券
手把手带您无忧上云