Skip to content

Instantly share code, notes, and snippets.

@naftulikay
Created May 31, 2016 02:48
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 naftulikay/a159dc21973ed998fc5eb6d2c83a79e4 to your computer and use it in GitHub Desktop.
Save naftulikay/a159dc21973ed998fc5eb6d2c83a79e4 to your computer and use it in GitHub Desktop.
Pipe a String into a Program's Input in Python
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
import subprocess
from StringIO import StringIO
def __main__():
parser = argparse.ArgumentParser(prog="piper", description="Pipes output of two programs together.")
parser.parse_args()
sio = StringIO("hello world\n")
p = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# await results of the pipe
output = p.communicate(input=sio.read())[0]
# outputs:
# rc:0, output:hello world
print("rc:{returncode}, output:{output}".format(returncode=p.returncode, output=output.strip()))
if __name__ == "__main__":
__main__()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment