How to capture the output from "subprocess.call" to a file?

The subprocess module has a built in 'check_output' function for doing this:

In [11]: result = subprocess.check_output(['pwd'])

In [12]: print result
/home/vagrant

import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()

import subprocess

try:
    result = subprocess.check_output(['dir', r'c:\temp'], shell=True)
    print result
except subprocess.CalledProcessError as e:
    return_code = e.returncode

You anyway need to use try catch because it throws exception if return code is non zero :)