Skip to content

Instantly share code, notes, and snippets.

@objcode
Created September 18, 2011 02:34
Show Gist options
  • Save objcode/1224642 to your computer and use it in GitHub Desktop.
Save objcode/1224642 to your computer and use it in GitHub Desktop.
python fail
def shell(cmdline):
start = time.time()
outbuffer = StringIO.StringIO()
print "asked to shell", cmdline
subcommands = cmdline.split('|')
subcommands = [command.strip() for command in subcommands]
first, last, subcommands = subcommands[0], subcommands[-1], subcommands[1:-1]
last_read, last_write = os.pipe()
subprocess.Popen(first, stdout=last_write, shell=True, executable="/bin/bash")
os.close(last_write)
print "made command", first
for command in subcommands:
print "adding ", command
next_read, next_write = os.pipe()
subprocess.Popen(command, stdout=next_write, stdin=last_read, shell=True, executable="/bin/bash")
os.close(next_write)
os.close(last_read)
last_read = next_read
print "making last command", last
mainread, mainwrite = os.pipe()
main = subprocess.Popen(last, stdout=mainwrite, stdin=last_read, shell=True, executable="/bin/bash")
os.close(mainwrite)
print "chain output:"
while True:
now = time.time()
if now - start > SHELL_TIMEOUT:
import math
raise ShellTimeout("'{}' timed out after {}ms".format(cmdline, math.floor(1000 * (now - start))))
out = os.read(mainread, 1)
sys.stdout.write(out)
sys.stdout.flush()
if out == '':
break
outbuffer.write(out)
while main.poll() is None:
print "waiting for {} to exit".format(last)
main.terminate()
main.kill()
time.sleep(0.1)
os.close(mainread)
return outbuffer.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment