Skip to content

Instantly share code, notes, and snippets.

@kei0425
Created November 15, 2017 02:28
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 kei0425/c32fe4c93b32b8e4af2b16e904e2a9fb to your computer and use it in GitHub Desktop.
Save kei0425/c32fe4c93b32b8e4af2b16e904e2a9fb to your computer and use it in GitHub Desktop.
python3で外部プログラムとstdin/stdoutで双方向通信を行う
import subprocess
class Execute(object):
"""外部プログラムを実行。stdinとstdoutで対話する。"""
def __init__(self, *args_1, **args_2):
if 'encoding' in args_2:
self.encoding = args_2.pop('encoding')
else:
self.encoding = 'utf-8'
self.popen = subprocess.Popen(*args_1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, **args_2)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def send(self, message, recieve=True, incr=False):
message = message.rstrip('\n')
if not incr and '\n' in message:
raise ValueError("message in \\n!")
self.popen.stdin.write((message + '\n').encode(self.encoding))
self.popen.stdin.flush()
if recieve:
return self.recieve()
return None
def recieve(self):
return self.popen.stdout.readline().decode(self.encoding)
def close(self):
self.popen.stdin.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment