Skip to content

Instantly share code, notes, and snippets.

@nojima
Created March 19, 2014 09:19
Show Gist options
  • Save nojima/9638262 to your computer and use it in GitHub Desktop.
Save nojima/9638262 to your computer and use it in GitHub Desktop.
指定されたコマンドを実行して、その出力にラベルを付与して出力するコマンド
#!/usr/bin/python
from argparse import ArgumentParser, REMAINDER
import os
import select
from subprocess import Popen, PIPE
import sys
def read_and_write(poll, rem, files, label):
for fd, _ in poll.poll():
buf = os.read(fd, 1024)
if len(buf) > 0:
lines = buf.split("\n")
lines[0] = rem[fd] + lines[0]
for line in lines[:-1]:
files[fd].write("[{}] {}\n".format(label, line))
rem[fd] = lines[-1]
else:
if len(rem[fd]) > 0:
files[fd].write("[{}] {}".format(label, rem[fd]))
poll.unregister(fd)
del rem[fd]
del files[fd]
def main():
parser = ArgumentParser(usage="label LABEL -- COMMAND...",
description="add LABEL to the output of COMMAND.")
parser.add_argument("label", metavar="LABEL",
help="a label added to each line of the output.")
parser.add_argument("command", metavar="COMMAND", nargs=REMAINDER,
help="a command to run.")
parser.print_usage = parser.print_help
args = parser.parse_args()
p = Popen(args.command, stdin=sys.stdin, stdout=PIPE, stderr=PIPE)
poll = select.poll()
poll.register(p.stdout)
poll.register(p.stderr)
rem = {p.stdout.fileno(): "", p.stderr.fileno(): ""}
files = {p.stdout.fileno(): sys.stdout, p.stderr.fileno(): sys.stderr}
while rem:
read_and_write(poll, rem, files, args.label)
p.wait()
sys.exit(p.returncode)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment