Skip to content

Instantly share code, notes, and snippets.

@reaaz
Created August 11, 2012 07:35
Show Gist options
  • Save reaaz/3322143 to your computer and use it in GitHub Desktop.
Save reaaz/3322143 to your computer and use it in GitHub Desktop.
Exec Command and Write Output to File
import os
import subprocess
def exec_with_output(command, command_dir, output_dir, output_filename):
"""Run command and write output to file
Args:
command: string, shell command to execute.
command_dir: string, directory to execute command from.
output_dir: string, directory to write output in.
output_filename: string, directory to write output in.
"""
# Make sure our directory exists.
try:
os.chdir(output_dir)
except:
os.makedirs(output_dir)
# Build our filename.
filename = os.path.normpath(output_dir + '/' + output_filename)
# Run the command.
proc = subprocess.Popen(
command + ' > ' + filename,
cwd=command_dir,
stderr=subprocess.STDOUT,
shell=True
)
exec_with_output('echo "Example"', '/tmp/', '/tmp/hello', 'hello.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment