Skip to content

Instantly share code, notes, and snippets.

@jsundram
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsundram/7344e09617521407fb9f to your computer and use it in GitHub Desktop.
Save jsundram/7344e09617521407fb9f to your computer and use it in GitHub Desktop.
A context-manager wrapper for running external binaries. Great for hiding scripts in other languages. Possibly an antipattern, but it works.
class Wrapper(object):
"""Communicate with a program via stdin/stdout.
Wrap the communication in python so it "feels" like native code.
See use by Runner, below.
"""
def __init__(self, script):
self.scriptname = os.path.basename(script)
self.p = Popen([script], stdin=PIPE, stdout=PIPE, bufsize=1)
print("%s initialized" % self.scriptname)
# Read the first line.
print(self.p.stdout.readline())
def __call__(self, json_blob):
try:
print(json_blob, file=self.p.stdin)
return self.p.stdout.readline()
except Exception as e:
print(e)
def terminate(self):
self.p.terminate()
print("%s terminated" % self.scriptname)
class Runner(object):
"""Communicate with a program via stdin/stdout.
Wrap the communication in python so it "feels" like native code.
i.e.
arguments = {} # some data
with Runner('/path/to/terrible.php') as run:
request = json.dumps(arguments)
result = run(request)
# do stuff with result
"""
def __init__(self, script):
self.script = Wrapper(script)
def __enter__(self):
return self
def __call__(self, json_blob):
return self.script(json_blob)
def __exit__(self, exc_type, exc_val, exc_tb):
self.script.terminate()
return False # Don't supress exceptions, if any.
#!/bin/env php
<?php
echo "terrible.php is ready!\n";
while (true) {
// Read args from stdin.
$arguments = json_decode(trim(fgets(STDIN)));
if ($arguments) {
$response = do_stuff($arguments);
// Write json to stdout.
echo json_encode($response, JSON_UNESCAPED_SLASHES|JSON_FORCE_OBJECT) . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment