Last active
January 8, 2018 15:59
-
-
Save Attumm/e726ccff378b23fa74d9a70c6664a3dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import subprocess | |
| import shlex | |
| import time | |
| import threading | |
| interval = 2 # in seconds | |
| command = 'ping 8.8.8.8' | |
| def print_(s): | |
| """2 and 3 compatible printing for most output. e.g don't use it. | |
| Use print without newline of your python version | |
| """ | |
| sys.stdout.write(s.decode("utf-8")) | |
| sys.stdout.flush() | |
| latest = None | |
| def run_command(command): | |
| global latest | |
| process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) | |
| while True: | |
| latest = process.stdout.readline() | |
| if latest == '' and process.poll() is not None: | |
| break | |
| rc = process.poll() | |
| return rc | |
| def print_output(interval=0): | |
| time.sleep(0.1) | |
| while True: | |
| time.sleep(interval) | |
| print_(latest) | |
| # instead of print send to the database | |
| runner = threading.Thread(target=run_command, args=[command,]) | |
| output = threading.Thread(target=print_output, args=[interval,]) | |
| runner.start() | |
| output.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment