Last active
July 9, 2018 08:43
-
-
Save ralt/401899907c0e6a3ac5eed793832cefbd to your computer and use it in GitHub Desktop.
Slow down stdout
This file contains 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
#!/usr/bin/env python | |
import gevent.monkey; gevent.monkey.patch_all() | |
import os.path | |
import sys | |
import tempfile | |
import threading | |
import time | |
import gevent | |
lines_per_second = float(sys.argv[1]) | |
wait_time = 1 / lines_per_second | |
tmpdir = tempfile.mkdtemp() | |
streaming_file = os.path.join(tmpdir, "slow-down") | |
def stdout_writer(stop_event): | |
with open(streaming_file, "rb") as stream: | |
while True: | |
for line in stream.readlines(): | |
sys.stdout.write(line) | |
time.sleep(wait_time) | |
if stop_event.is_set(): | |
break | |
try: | |
stop_event = threading.Event() | |
with open(streaming_file, "ab") as stream: | |
writer = gevent.spawn(stdout_writer, stop_event) | |
for line in sys.stdin.readlines(): | |
stream.write(line) | |
stop_event.set() | |
writer.join() | |
except KeyboardInterrupt: | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment