16

I'm calling a python script (B) from another python script (A).

Using subprocess.call, how do I redirect the stdout of B to a file that specify?

I'm using python 2.6.1.

2
  • 2
    Why are you using subprocess.call() to execute another Python script? Wouldn't it be better to import it and call the appropriate functions? Commented Feb 19, 2012 at 5:40
  • Script B is a wrapper script that is calling A to which I want to send a list of arguments that I'm iterating through. Commented Feb 19, 2012 at 5:49

2 Answers 2

50

Pass a file as the stdout parameter to subprocess.call:

with open('out-file.txt', 'w') as f:
    subprocess.call(['program'], stdout=f)
Sign up to request clarification or add additional context in comments.

1 Comment

...and this reminded me that I can also put stderr=f.
2

Alternate approach

import subprocess
p=subprocess.Popen('lsblk -l|tee a.txt',stdout=subprocess.PIPE,shell=True)
(output,err)=p.communicate()
p_status=p.wait()
print output

Above code will write output of command to file a.txt

2 Comments

This one is useful if for some strange reason you need the subprocess to be in control of the file, not python (my case)
...though that can, and should, still be done without shell=True; you can have two separate Popen objects, one for lsblk and a second one for tee, with the first's stdout connected to the second's stdin; the subprocess module docs show how to do so.

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.