Minh Nghĩa
Minh Nghĩa

Reputation: 1053

Cannot redirect IO using popen

I cannot use output redirect in using Popen. Here's the problematic code:

subprocess.Popen(['program'
                  'arg', #arguments
                  '0',
                  '&> program.out'])

The program runs, but the stdout and stderr doesn't get routed to the output file. Furthermore, the last argument was concatenated with the redirect command as a single argument (0&> program.out in this case). When I join the commands together and pass the whole command string to Popen, with shell=True, things go smoothly, but I think this might not the recommended way to use Popen.

Upvotes: 1

Views: 60

Answers (1)

Sam Mason
Sam Mason

Reputation: 16174

&> filename syntax is Bourne shell (e.g. bash) syntax, you'd probably want to do something closer to:

with open('program.out', 'w') as fd:
  subprocess.Popen(['program', 'arg'], stdout=fd, stderr=fd)

as per the docs for stdout and stderr:

Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None.

where the code above is just passing "an existing file object"

Upvotes: 1

Related Questions