How to redirect output to a file in a .Popen subprocess

I tried this code to redirect standard output to a file:

subprocess.Popen('my command', cwd='my path', shell=True, stdout=stdout.txt, stderr=stdout.txt)

But there was an error: NameError: name 'stdout' is not defined

I am using python version 2.5.2

+4
source share
2 answers

First open the file and use ato add if you want to keep a record of all output / errors or use wto overwrite every time:

with open("stdout.txt","a+") as stdout:
   subprocess.Popen('my command', cwd='my path', shell=True, stdout=stdout, stderr=stdout)

Using withwill automatically close your file.

+7
source

Give a file descriptor for stdout See document

0
source

All Articles