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?
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?
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)
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
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.