Skip to content

Instantly share code, notes, and snippets.

@filipsPL
Created November 7, 2018 20:29
Show Gist options
  • Save filipsPL/39be96743d4bb9fd9691791138d73459 to your computer and use it in GitHub Desktop.
Save filipsPL/39be96743d4bb9fd9691791138d73459 to your computer and use it in GitHub Desktop.
Function which: 1) runs the command 2) for the specified time (duration) and 3) pipes output to the file AND to screen (live).
import time
from time import strftime
import subprocess
def runForDuration(cmdline, duration, logFile):
teeCommand = ['tee', '-a', logFile ] # quick and dirty hack to get log to file
try:
p1 = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p2 = subprocess.Popen(teeCommand, stdin=p1.stdout)
time.sleep(duration)
p1.terminate()
except OSError as e:
print "✖ OS Error during command: " + " ".join(cmdline)
print "✖ OS Error: " + e.strerror
runForDuration(['ping', 'github.com'], 10, "logfile.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment