38 lines
941 B
Python
38 lines
941 B
Python
import asyncio
|
|
from asyncio import subprocess
|
|
import psutil
|
|
from typing import Callable
|
|
|
|
|
|
def kill(proc_pid):
|
|
try:
|
|
process = psutil.Process(proc_pid)
|
|
for proc in process.children(recursive=True):
|
|
proc.kill()
|
|
process.kill()
|
|
except psutil.NoSuchProcess:
|
|
return
|
|
|
|
|
|
async def run_process(
|
|
command: str, env: dict,
|
|
try_to_fix_flush: bool = True
|
|
) -> subprocess.Process:
|
|
process = await subprocess.create_subprocess_shell(
|
|
cmd=command,
|
|
env=env | {"PYTHONUNBUFFERED": "1"} if try_to_fix_flush else env,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
|
|
return process
|
|
|
|
|
|
async def stream_handler(stream: asyncio.streams.StreamReader, real_handler: Callable):
|
|
while True:
|
|
line = (await stream.readline()).decode().strip()
|
|
if not line:
|
|
return
|
|
await real_handler(line)
|