2

In python 2.7, I would like to execute an OS command (for example 'ls -l' in UNIX) and save its output to a file. I don't want the execution results to show anywhere else other than the file.

Is this achievable without using os.system?

lisa1987
  • 545
  • 1
  • 5
  • 14
  • What do you mean "hide the execution results from stdout"? Do you just want those results to go into a file and not show up on the screen/other place in your program? – Eric Renouf Jun 06 '15 at 13:19
  • @eric Indeed, I don't want the results to show up on the screen or anywhere else other than the file. – lisa1987 Jun 06 '15 at 13:21
  • Do you want to redirect just standard output or both standard output and standard error ? – Serge Ballesta Jun 06 '15 at 13:23

3 Answers3

3

Use subprocess.check_call redirecting stdout to a file object:

from subprocess import check_call, STDOUT, CalledProcessError

with open("out.txt","w") as f:
    try:
        check_call(['ls', '-l'], stdout=f, stderr=STDOUT)
    except CalledProcessError as e:
        print(e.message)

Whatever you what to do when the command returns a non-zero exit status should be handled in the except. If you want a file for stdout and another to handle stderr open two files:

from subprocess import check_call, STDOUT, CalledProcessError, call

with open("stdout.txt","w") as f, open("stderr.txt","w") as f2:
    try:
        check_call(['ls', '-l'], stdout=f, stderr=f2)
    except CalledProcessError as e:
        print(e.message)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

Assuming you just want to run a command have its output go into a file, you could use the subprocess module like

subprocess.call( "ls -l > /tmp/output", shell=True )

though that will not redirect stderr

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

You can open a file and pass it to subprocess.call as the stdout parameter and the output destined for stdout will go to the file instead.

import subprocess

with open("result.txt", "w") as f:
    subprocess.call(["ls", "-l"], stdout=f)

It wont catch any output to stderr though that would have to be redirected by passing a file to subprocess.call as the stderr parameter. I'm not certain if you can use the same file.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61