Spaces:
Running
Running
from flask import Flask, request, render_template_string | |
import subprocess | |
import sys | |
import os | |
app = Flask(__name__) | |
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; } | |
</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"> | |
</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 %} | |
</body> | |
</html> | |
""" | |
def run_code(): | |
code = "" | |
output = "" | |
error = "" | |
warning = "" | |
if request.method == "POST": | |
code = request.form.get("code", "") | |
# Check if code contains Toga imports | |
if "import toga" in code or "from toga" in code: | |
warning = ("Toga apps create GUI windows, which cannot be displayed in a web browser. " | |
"The code will run, but the GUI will appear on the server (if a display is available). " | |
"Consider downloading the code to run locally.") | |
# Write the code to a temporary file | |
temp_file = "temp_code.py" | |
with open(temp_file, "w") as f: | |
f.write(code) | |
try: | |
# Run the code in a subprocess with restricted environment | |
result = subprocess.run( | |
[sys.executable, temp_file], | |
capture_output=True, | |
text=True, | |
timeout=5 # Short timeout for GUI apps to avoid hanging | |
) | |
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: | |
# Clean up the temporary file | |
if os.path.exists(temp_file): | |
os.remove(temp_file) | |
return render_template_string(HTML_TEMPLATE, code=code, output=output, error=error, warning=warning) | |
if __name__ == "__main__": | |
app.run(debug=True, host="0.0.0.0", port=7860) |