Skip to content

Instantly share code, notes, and snippets.

@asilbalaban
Created August 14, 2022 20:25
Show Gist options
  • Save asilbalaban/636fcc20430a9a8fec5eed0ad684f7aa to your computer and use it in GitHub Desktop.
Save asilbalaban/636fcc20430a9a8fec5eed0ad684f7aa to your computer and use it in GitHub Desktop.
Read realtime output with python subprocess
import os
import subprocess
import fcntl
import time
def non_block_read(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.readline()
except:
return ""
def run_process(cmd):
with subprocess.Popen(cmd, shell=False, universal_newlines=True, encoding='utf-8', bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
while True:
out = non_block_read(p.stdout)
err = non_block_read(p.stderr)
if out:
print(out, end='')
# this is for socket broadcasting
# socketio.emit('console-response', out)
if err:
# this is for socket broadcasting
# socketio.emit('console-response', err)
print('E: ' + err, end='')
if p.poll() is not None:
break
time.sleep(0.0001)
if __name__ == "__main__":
path = os.path.dirname(os.path.abspath(__file__))
script = path + "/debug.py"
cmd = ['/usr/bin/python3', script, 'ORD-', '6']
run_process(cmd)
import sys
import time
import random
def run(startWith, howManyTimes):
for i in range(0, howManyTimes):
randomString = ''.join(random.choice('0123456789') for i in range(10))
sys.stdout.write(startWith + randomString + '\n')
sys.stdout.flush()
time.sleep(1)
if __name__ == '__main__':
startWith = "ORDER-"
howManyTimes = 10
if len(sys.argv) > 1:
startWith = sys.argv[1]
if len(sys.argv) > 2:
howManyTimes = int(sys.argv[2])
run(startWith, howManyTimes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment