Created
August 23, 2011 17:11
-
-
Save aerosol/1165884 to your computer and use it in GitHub Desktop.
Stdin pipe wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import sys | |
| import time | |
| import os | |
| import resource | |
| import subprocess | |
| def spawn(proc): | |
| kw = { | |
| 'stdin': subprocess.PIPE, | |
| 'stdout': open('stdout.log', 'a+'), | |
| 'stderr': open('stderr.log', 'a+') | |
| } | |
| return subprocess.Popen(proc.split(), **kw) | |
| def touch_stdin(stdin_f): | |
| if not os.path.exists(stdin_f): | |
| open(stdin_f, "w+").close() | |
| return stdin_f | |
| def wait_for_stdin(p, stdin_f): | |
| f = open(stdin_f, "r") | |
| while p.returncode is None: | |
| time.sleep(0.1) | |
| l = f.readline() | |
| if l.strip(): | |
| p.stdin.write("%s" % l) | |
| p.stdin.flush() | |
| p.poll() | |
| f.close() | |
| return p.returncode | |
| if __name__ == '__main__': | |
| try: | |
| assert len(sys.argv) == 3, \ | |
| 'Usage: %s "command" stdin_file' % sys.argv[0] | |
| (p, f) = sys.argv[1:] | |
| ec = wait_for_stdin(spawn(p), touch_stdin(f)) | |
| assert ec == 0, \ | |
| 'Abnormal termination - exit code: %d' % ec | |
| except Exception, e: | |
| print str(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment