Skip to content

Instantly share code, notes, and snippets.

@tyfkda
Created April 12, 2016 07:57
Show Gist options
  • Save tyfkda/2fb14d155e9b8196f58c629990c84104 to your computer and use it in GitHub Desktop.
Save tyfkda/2fb14d155e9b8196f58c629990c84104 to your computer and use it in GitHub Desktop.
Run command and handle pipes.
import subprocess
def run(command, input=None):
try:
process = subprocess.Popen(
command, stdin=subprocess.PROCESS,
stdout=subprocess.PROCESS, stderr=subprocess.PROCESS,
close_fds=True)
if input:
process.stdin.write(input)
process.stdin.close()
result = process.stdout.read()
ret = process.wait()
return ret, result
except OSError, (e):
return (e.errno, e.args[1])
print run(['ls', '-1']) # (0, 'run.py\n')
print run('sort', 'hoge\nfuga\npiyo\n') # (0, 'fuga\nhoge\npiyo\n')
print run('hoge') # (2, 'No such file or directory')
print run(['rm', 'non-exist.txt']) # (1, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment