Skip to content

Instantly share code, notes, and snippets.

@yatsu
Last active January 4, 2017 14:45
Show Gist options
  • Save yatsu/3215bcb3b7cbe5caaee0916f8e94a2e5 to your computer and use it in GitHub Desktop.
Save yatsu/3215bcb3b7cbe5caaee0916f8e94a2e5 to your computer and use it in GitHub Desktop.
Read tornado.process.Subprocess stdout
#!/bin/bash
sleep_sec=0
usage() {
echo "Usage: $0 [-s sleep_sec] <num>"
}
while getopts :s:h OPT; do
case $OPT in
s) sleep_sec=$OPTARG
;;
h) usage
exit
;;
\?) usage 1>&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [ -z "$1" ]; then
usage 1>&2
exit 1
fi
set -eu
for i in $(seq $1); do
sleep $sleep_sec
echo $(($1 - $i))
done
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
import os
import shlex
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.process import Subprocess
from tornado.log import enable_pretty_logging
from tornado.iostream import StreamClosedError
command = '{0}/countdown.sh -s 1 5'.format(os.getcwd())
@gen.coroutine
def run_subproc():
proc = Subprocess(shlex.split(command), stdout=Subprocess.STREAM)
try:
while True:
line = yield proc.stdout.read_until(b'\n')
logging.info('read: %s', line.decode('ascii')[:-1])
except StreamClosedError:
pass
except Exception as e:
logging.error('Error: %s', e)
finally:
IOLoop.current().stop()
if __name__ == '__main__':
enable_pretty_logging()
loop = IOLoop.current()
loop.add_callback(run_subproc)
loop.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment