Skip to content

Instantly share code, notes, and snippets.

@giuliano-macedo
Last active August 19, 2019 13:43
Show Gist options
  • Save giuliano-macedo/40e36364e8f31f881a94eb2a5d2bcd83 to your computer and use it in GitHub Desktop.
Save giuliano-macedo/40e36364e8f31f881a94eb2a5d2bcd83 to your computer and use it in GitHub Desktop.
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