2

In my Python code, I have

executable_filepath = '/home/user/executable'
input_filepath = '/home/user/file.in'

I want to analyze the output I would get in shell from command

/home/user/executable </home/user/file.in

I tried

command = executable_filepath + ' <' + input_filepath
p = subprocess.Popen([command], stdout=subprocess.PIPE)
p.wait()
output = p.stdout.read()

but it doesn't work. The only solution that I can think of now is creating another pipe, and copying input file through it, but there must be a simple way.

2 Answers 2

6
from subprocess import check_output

with open("/home/user/file.in", "rb") as file:
    output = check_output(["/home/user/executable"], stdin=file)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to specify shell=True in the call to Popen. By default, [command] is passed directly to a system call in the exec family, which doesn't understand shell redirection operators.

Alternatively, you can let Popen connect the process to the file:

with open(input_filepath, 'r') as input_fh:
    p = subprocess.Popen( [executable_filepath], stdout=subprocess.PIPE, stdin=input_fh)
    p.wait()
    output=p.stdout.read()

1 Comment

calling .wait() before .stdout.read() can lead to a deadlock if the subprocess generates enough output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.