Created
April 12, 2016 07:57
-
-
Save tyfkda/2fb14d155e9b8196f58c629990c84104 to your computer and use it in GitHub Desktop.
Run command and handle pipes.
This file contains hidden or 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
| 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