try:
    file = open('somefile', 'rb', 0)
except FileNotFoundError:
    file = io.BytesIO('somefile not found')

def write_input(source, sink):
    with source:
        with sink:
            copyfileobj(source, sink)
cmd = ['grep', 'o']
with Popen(cmd, stdin=PIPE, stdout=PIPE) as process:
    Thread(target=write_input, args=(file, process.stdin), daemon=True).start()
output = process.stdout.read()
Use StringIO as stdin with Popen