43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import asyncio
|
|
import subprocess
|
|
from fastapi import APIRouter
|
|
from fastapi.responses import StreamingResponse
|
|
|
|
|
|
test = APIRouter()
|
|
|
|
|
|
async def generate_data():
|
|
for i in range(1, 10): # 生成 5 行数据
|
|
await asyncio.sleep(1) # 等待 1 秒
|
|
yield f"data: This is line {i}\n\n" # 返回 SSE 格式的数据
|
|
|
|
|
|
def run_command(command):
|
|
"""执行命令并实时打印每一行输出"""
|
|
# 启动子进程
|
|
with subprocess.Popen(
|
|
command,
|
|
shell=True,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
universal_newlines=True, # 确保输出以字符串形式返回而不是字节
|
|
bufsize=1, # 行缓冲
|
|
) as process:
|
|
# 使用iter逐行读取stdout和stderr
|
|
for line in process.stdout:
|
|
yield f"stdout: {line.strip()} \n"
|
|
|
|
for line in process.stderr:
|
|
yield f"stderr: {line.strip()} \n"
|
|
|
|
# 等待进程结束并获取返回码
|
|
return_code = process.wait()
|
|
if return_code != 0:
|
|
print(f"Process exited with non-zero code: {return_code}")
|
|
|
|
|
|
@test.get("/stream")
|
|
async def stream_response():
|
|
return StreamingResponse(run_command(["ping", "-n", "10", "127.0.0.1"]), media_type="text/plain")
|