0

Possible Duplicate:
Pipe subprocess standard output to a variable

I am running a python program :

import os
os.system("ls") # ls command runs on the terminal 

To store the output in a file :

os.system("ls > a.txt")

What I need is, it stores the output in some temporary string . IS THAT POSSIBLE ??

Community
  • 1
  • 1
sammyiitkgp
  • 249
  • 5
  • 11
  • No. You can't do that. Read the content of a.txt into a variable after the system call. Better yet use python pipes. – SidJ Jul 03 '12 at 06:56
  • 3
    @SridharJagannathan You are wrong. Of course you can do that, using the subprocess module of python. – sloth Jul 03 '12 at 06:58
  • @BigYellowCactus I did mention pipes. – SidJ Jul 03 '12 at 08:16

1 Answers1

5
import subprocess
output = subprocess.Popen(["ls"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]

Here you run the external command ls and redirects both the stderr and stdout strewams of the command to the variable output.

Where the streams have to be redirected are specified using the arguments stdout and stderr of the Popen function.

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144