Spaces:
Sleeping
Sleeping
from flask import Flask, render_template | |
from flask_socketio import SocketIO, emit | |
import subprocess | |
import os | |
app = Flask(__name__) | |
app.config['SECRET_KEY'] = 'secret!' | |
socketio = SocketIO(app) | |
# 设置工作目录 | |
WORKING_DIR = '/tmp' | |
def index(): | |
return render_template('index.html') | |
def handle_command(command): | |
try: | |
# 切换到工作目录 | |
os.chdir(WORKING_DIR) | |
# 执行命令并捕获输出 | |
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) | |
while True: | |
output = process.stdout.readline() | |
if output == '' and process.poll() is not None: | |
break | |
if output: | |
emit('command_output', {'output': output.strip()}) | |
# 捕获错误输出 | |
error = process.stderr.read() | |
if error: | |
emit('command_output', {'output': error.strip()}) | |
# 发送命令执行结束信号 | |
emit('command_output', {'output': '[Command execution finished]'}) | |
except Exception as e: | |
emit('command_output', {'output': str(e)}) | |
if __name__ == '__main__': | |
socketio.run(app, host='0.0.0.0', port=7860, allow_unsafe_werkzeug=True) |