Spaces:
Running
Running
from flask import Flask, request, render_template_string | |
import subprocess | |
import sys | |
import os | |
app = Flask(__name__) | |
def run_code(): | |
code = "" | |
output = "" | |
error = "" | |
warning = "" | |
iframe = "" | |
if request.method == "POST": | |
code = request.form.get("code", "") | |
if "import toga" in code or "from toga" in code: | |
warning = ("Toga apps create GUI windows, which run on the server's virtual display. " | |
"View the GUI below (may take a moment to load). Download the code to run locally.") | |
iframe = '<iframe src=":6080" width="800" height="600" frameborder="0"></iframe>' | |
temp_file = "temp_code.py" | |
with open(temp_file, "w") as f: | |
f.write(code) | |
try: | |
result = subprocess.run( | |
[sys.executable, temp_file], | |
capture_output=True, | |
text=True, | |
timeout=5 | |
) | |
output = result.stdout | |
error = result.stderr | |
except subprocess.TimeoutExpired: | |
error = "Execution timed out after 5 seconds." | |
except Exception as e: | |
error = f"An error occurred: {str(e)}" | |
finally: | |
if os.path.exists(temp_file): | |
os.remove(temp_file) | |
return render_template_string(HTML_TEMPLATE, code=code, output=output, error=error, warning=warning, iframe=iframe) | |
# Update HTML_TEMPLATE to include iframe | |
HTML_TEMPLATE = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Python Code Runner</title> | |
<style> | |
body { font-family: Arial, sans-serif; margin: 20px; } | |
textarea { width: 100%; height: 300px; } | |
pre { background: #f4f4f4; padding: 10px; border: 1px solid #ddd; } | |
.error { color: red; } | |
.warning { color: orange; } | |
iframe { margin-top: 20px; } | |
</style> | |
</head> | |
<body> | |
<h1>Python Code Runner</h1> | |
<form method="POST" action="/"> | |
<textarea name="code" placeholder="Paste your Python code here">{{ code }}</textarea><br> | |
<input type="submit" value="Run Code"> | |
<a href="/download?code={{ code | urlencode }}"><button>Download Code</button></a> | |
</form> | |
{% if warning %} | |
<h2 class="warning">Warning:</h2> | |
<pre class="warning">{{ warning }}</pre> | |
{% endif %} | |
{% if output %} | |
<h2>Output:</h2> | |
<pre>{{ output }}</pre> | |
{% endif %} | |
{% if error %} | |
<h2 class="error">Error:</h2> | |
<pre class="error">{{ error }}</pre> | |
{% endif %} | |
{{ iframe | safe }} | |
</body> | |
</html> | |
""" | |
if __name__ == "__main__": | |
app.run(debug=True, host="0.0.0.0", port=7860) |