Guest User

Untitled

a guest
Jan 16th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. import sys
  2. import subprocess
  3. import shlex
  4. import time
  5. import threading
  6.  
  7. interval = 2 # in seconds
  8. command = 'ping 8.8.8.8'
  9.  
  10. def print_(s):
  11. """2 and 3 compatible printing for most output. e.g don't use it.
  12. Use print without newline of your python version
  13. """
  14. sys.stdout.write(s.decode("utf-8"))
  15. sys.stdout.flush()
  16.  
  17. latest = None
  18. def run_command(command):
  19. global latest
  20. process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
  21. while True:
  22. latest = process.stdout.readline()
  23. if latest == '' and process.poll() is not None:
  24. break
  25. rc = process.poll()
  26. return rc
  27.  
  28.  
  29. def print_output(interval=0):
  30. time.sleep(0.1)
  31. while True:
  32. time.sleep(interval)
  33. print_(latest)
  34. # instead of print send to the database
  35.  
  36. runner = threading.Thread(target=run_command, args=[command,])
  37. output = threading.Thread(target=print_output, args=[interval,])
  38.  
  39. runner.start()
  40. output.start()
Add Comment
Please, Sign In to add comment