不幸的是,“简单”并不能解决所有涉及的极端情况,您需要阅读子流程
stdout
在流媒体播放时,将其打印出来
和
将其累积在缓冲区中,并跟踪时间,以便正确超时。请注意,如果4096字节的读取恰好以多行字符结尾,这也可能存在错误(尽管不是很危险)。
def run_shell_command(command: list, debug: bool = False, timeout: float = 5):
"""
Run shell command
:param command: Shell command
:param debug: Debug mode
:return: Result code and message
"""
with subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) as process:
start_time = time.time()
output = b""
while True:
buf = process.stdout.read(4096)
if debug:
# could fail if `buf` happens to end in a multi-byte character
print(buf.decode("utf-8", "ignore"))
output += buf
if time.time() - start_time > timeout:
process.kill()
message = "Shell command timed out"
return {"code": 500, "msg": message, "stdout": output}
if process.poll() is not None:
break
if process.returncode != 0:
message = "Shell command failed"
return {"code": 500, "msg": message, "stdout": output}
message = "Shell command executed successfully"
return {"code": 200, "msg": message, "stdout": output}
if __name__ == "__main__":
command = run_shell_command(["ls", "-lah"], True)
print(command)