Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get ping realtime stdout and exit code in python using forkpty and execvp
import os
def bash_real_time(command):
pid,fd = os.forkpty()
if pid == 0:
os.execv('/bin/bash',['bash','-c',command])
exit(0)
while True:
try:
output = os.read(fd,1024).decode("utf-8").rstrip()
except Exception:
break
for line in output.split("\n"):
yield line
pid,status,res_usage=os.wait4(pid,0)
exit_code=os.WEXITSTATUS(status)
if exit_code!=0:
raise OSError(exit_code)
for line in bash_real_time("ping -c 5 127.0.0.1"):
print(f"[PING] {line}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment