Skip to content

Instantly share code, notes, and snippets.

@simonhayward
Created September 26, 2011 16:42
Show Gist options
  • Save simonhayward/1242688 to your computer and use it in GitHub Desktop.
Save simonhayward/1242688 to your computer and use it in GitHub Desktop.
Run command + script as I make changes to file
import os
import sys
import subprocess
import time
def file_is_modified(filename):
""" Accepts & returns filename if it has been modified """
previous_st_mtime = 0
while True:
st_mtime = os.stat(filename)[8]
if not st_mtime > previous_st_mtime:
time.sleep(0.1)
continue
previous_st_mtime = st_mtime
yield filename
def exec_with_file_output(command, filename):
""" Take command and filename - check if modified, yields output """
for modified_filename in file_is_modified(filename):
process = subprocess.Popen([command, modified_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
yield (process.pid, process.communicate())
def print_output_with_seperator(data, count = 40, word = ''):
""" Output + seperator for pretty print """
if data:
print count * '-' + word + count * '-'
print data
if __name__=="__main__":
try:
for output in exec_with_file_output(sys.argv[1], sys.argv[2]):
pid, stdoutdata, stderrdata = output[0], output[1][0], output[1][1],
print_output_with_seperator(stdoutdata, word='stdout for pid: %d' % pid)
print_output_with_seperator(stderrdata, word='stderr for pid: %d' % pid)
except (IndexError, OSError) as e:
print 'Supply [command] [filename]\n%s' % e
except KeyboardInterrupt:
print 'Exiting...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment