Python Popen sending to process on stdin, receiving on stdout
Asked Answered
U

1

11

I pass an executable on the command-line to my python script. I do some calculations and then I'd like to send the result of these calculations on STDIN to the executable. When it has finished I would like to get the executable's result back from STDOUT.

ciphertext = str(hex(C1))
exe = popen([sys.argv[1]], stdout=PIPE, stdin=PIPE)
result = exe.communicate(input=ciphertext)[0]
print(result)

When I print result I get nothing, not None, an empty line. I'm sure that the executable works with the data as I've repeated the same thing using the '>' on the command-line with the same previously calculated result.

Uitlander answered 3/4, 2013 at 10:41 Comment(2)
Are you certain that you have tested that the executable works even without a newline at the end of the input? ("echo" will add a newline, "echo -n" will not.)Extrauterine
@Extrauterine yep, works with newline as wellUitlander
S
20

A working example

#!/usr/bin/env python
import subprocess
text = 'hello'
proc = subprocess.Popen(
    'md5sum',stdout=subprocess.PIPE,
    stdin=subprocess.PIPE)
proc.stdin.write(text)
proc.stdin.close()
result = proc.stdout.read()
print result
proc.wait()

to get the same thing as “execuable < params.file > output.file”, do this:

#!/usr/bin/env python
import subprocess
infile,outfile = 'params.file','output.file'
with open(outfile,'w') as ouf:
    with open(infile,'r') as inf:
        proc = subprocess.Popen(
            'md5sum',stdout=ouf,stdin=inf)
        proc.wait()
Solatium answered 3/4, 2013 at 11:2 Comment(1)
Still same result, empty line. Is Popen actually the same as '<' on the command-line? I'm trying to recreate this: oracle.exe < params.file > output.fileUitlander

© 2022 - 2024 — McMap. All rights reserved.