Spaces:
BG5
/
Sleeping

BG5 commited on
Commit
95ce585
·
verified ·
1 Parent(s): e44d5f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -29
app.py CHANGED
@@ -1,43 +1,37 @@
1
  from flask import Flask, render_template
2
  from flask_socketio import SocketIO, emit
3
- import subprocess
4
  import os
 
 
5
 
6
  app = Flask(__name__)
7
- app.config['SECRET_KEY'] = 'secret!'
8
  socketio = SocketIO(app)
9
 
10
- # 设置工作目录
11
- WORKING_DIR = '/tmp'
 
 
 
 
 
 
 
 
 
12
 
13
  @app.route('/')
14
  def index():
15
  return render_template('index.html')
16
 
17
- @socketio.on('execute_command')
18
- def handle_command(command):
19
- try:
20
- # 切换到工作目录
21
- os.chdir(WORKING_DIR)
22
-
23
- # 执行命令并捕获输出
24
- process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
25
- while True:
26
- output = process.stdout.readline()
27
- if output == '' and process.poll() is not None:
28
- break
29
- if output:
30
- emit('command_output', {'output': output.strip()})
31
-
32
- # 捕获错误输出
33
- error = process.stderr.read()
34
- if error:
35
- emit('command_output', {'output': error.strip()})
36
-
37
- # 发送命令执行结束信号
38
- emit('command_output', {'output': '[Command execution finished]'})
39
- except Exception as e:
40
- emit('command_output', {'output': str(e)})
41
 
42
  if __name__ == '__main__':
43
- socketio.run(app, host='0.0.0.0', port=7860, allow_unsafe_werkzeug=True)
 
 
 
 
1
  from flask import Flask, render_template
2
  from flask_socketio import SocketIO, emit
3
+ import pty
4
  import os
5
+ import subprocess
6
+ import threading
7
 
8
  app = Flask(__name__)
9
+ app.config['SECRET_KEY'] = 'your_secret_key'
10
  socketio = SocketIO(app)
11
 
12
+ def run_shell():
13
+ master_fd, slave_fd = pty.openpty()
14
+ process = subprocess.Popen(['bash'], stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, text=True)
15
+
16
+ while True:
17
+ output = os.read(master_fd, 1024).decode('utf-8')
18
+ if output:
19
+ socketio.emit('output', output)
20
+
21
+ # 这里可以添加一个小的延迟,避免CPU占用过高
22
+ socketio.sleep(0.1)
23
 
24
  @app.route('/')
25
  def index():
26
  return render_template('index.html')
27
 
28
+ @socketio.on('input')
29
+ def handle_input(input_data):
30
+ # 将输入写入伪终端
31
+ os.write(shell_master_fd, (input_data + '\n').encode('utf-8'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  if __name__ == '__main__':
34
+ shell_master_fd, shell_slave_fd = pty.openpty()
35
+ shell_thread = threading.Thread(target=run_shell)
36
+ shell_thread.start()
37
+ socketio.run(app, host='0.0.0.0', port=7860)