Last active
August 29, 2015 14:07
-
-
Save asauber/97e5a1c6a1ef8f1db7a6 to your computer and use it in GitHub Desktop.
Read a random line from a file, supporting stdin
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 random | |
import sys | |
def random_line(file_handle): | |
lines = file_handle.readlines() | |
num_lines = len(lines) | |
random_line = None | |
while not random_line: | |
random_line_num = random.randint(0, num_lines - 1) | |
random_line = lines[random_line_num] | |
random_line = random_line.strip() | |
return random_line | |
file_handle = None | |
if len(sys.argv) < 2: | |
sys.stderr.write("Reading stdin\n") | |
file_handle = sys.stdin | |
else: | |
file_handle = open(sys.argv[1]) | |
print(random_line(file_handle)) | |
file_handle.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment