1

I have an input file called 0.in. To get the output I do ./a.out < 0.in in the Bash Shell.

Now, I have several such files (more than 500) and I want to automate this process using Python's subprocess module.

I tried doing this:

data=subprocess.Popen(['./a.out','< 0.in'],stdout=subprocess.PIPE,stdin=subprocess.PIPE).communicate()

Nothing was printed (data[0] was blank) when I ran this. What is the right method to do what I want to do?

1 Answer 1

2

Redirection using < is a shell feature, not a python feature.

There are two choices:

  1. Use shell=True and let the shell handle redirection:

    data = subprocess.Popen(['./a.out < 0.in'], stdout=subprocess.PIPE, shell=True).communicate()
    
  2. Let python handle redirection:

    with open('0.in') as f:
        data = subprocess.Popen(['./a.out'], stdout=subprocess.PIPE, stdin=f).communicate()
    

The second option is usually preferred because it avoids the vagaries of the shell.

If you want to capture stderr in data, then add stderr=subprocess.PIPE to the Popen command. Otherwise, stderr will appear on the terminal or wherever python's error messages are being sent.

Sign up to request clarification or add additional context in comments.

2 Comments

@Rayu Since the second method does not spawn a shell, I expect it to be faster and also use less memory.
don't use a list argument and shell=True together -- it is misleading (always pass a string instead). You could use subprocess.check_output(['./a.out'], stdin=f) here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.