Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how redirect output to the file in subprocess.Popen

Tags:

python

stdout

I tried such code to redirect standart output to the file:

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

But got error: NameError: name 'stdout' is not defined

I use python version 2.5.2

like image 363
khris Avatar asked Jul 28 '14 13:07

khris


2 Answers

Open the file first and use a to append if you want to keep a record of all output/errors or use w to overwrite each time:

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

Using with will automatically close your file.

like image 194
Padraic Cunningham Avatar answered Oct 12 '22 23:10

Padraic Cunningham


Give a file descriptor to stdout See doc

like image 32
log0 Avatar answered Oct 13 '22 01:10

log0