【发布时间】:2019-01-27 17:58:57
【问题描述】:
我正在创建一个 API 来执行命令行命令。服务器实际上只有两种方法,“运行”和“停止”。所以,“运行”的主要功能是在服务器端运行一个命令行程序,并返回一个带有系统输出的列表。另一方面,“停止”功能只是杀死正在运行的进程。代码如下:
import sys
import json
import subprocess
from klein import Klein
class ItemStore(object):
app = Klein()
current_process = None
def __init__(self):
self._items = {}
def create_process(self, exe):
"""
Run command and return the system output inside a JSON string
"""
print("COMMAND: ", exe)
process = subprocess.Popen(exe, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self.current_process = process
# Poll process for new output until finished
output_lines = []
counter = 0
while True:
counter = counter + 1
nextline = process.stdout.readline()
if process.poll() is not None:
break
aux = nextline.decode("utf-8")
output_lines.append(aux)
sys.stdout.flush()
counter = counter + 1
print("RETURN CODE: ", process.returncode)
return json.dumps(output_lines)
@app.route('/run/<command>', methods=['POST'])
def run(self, request, command):
"""
Execute command line process
"""
exe = command
print("COMMAND: ", exe)
output_lines = self.create_process(exe)
request.setHeader("Content-Type", "application/json")
request.setResponseCode(200)
return output_lines
@app.route('/stop', methods=['POST'])
def stop(self, request):
"""
Kill current execution
"""
self.current_process.kill()
request.setResponseCode(200)
return None
if __name__ == '__main__':
store = ItemStore()
store.app.run('0.0.0.0', 15508)
好吧,这样的问题是,如果我需要停止当前的执行,“停止”请求将在“运行”请求完成之前不会出现,所以以这种方式工作是没有意义的。我已经阅读了几页关于 async/await 解决方案的内容,但我无法让它工作!我认为最突出的解决方案是在这个网页https://crossbario.com/blog/Going-Asynchronous-from-Flask-to-Twisted-Klein/ 中,但是,“运行”仍然是一个同步过程。我只是发布了我的主要和原始代码,以免与网页更改混淆。
最好的问候
【问题讨论】:
标签: python api asynchronous twisted