Last active
August 29, 2015 14:21
-
-
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.
This file contains 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
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. | |
This file contains 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
#!/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