Skip to content

Instantly share code, notes, and snippets.

@asauber
Last active August 29, 2015 14:07
Show Gist options
  • Save asauber/97e5a1c6a1ef8f1db7a6 to your computer and use it in GitHub Desktop.
Save asauber/97e5a1c6a1ef8f1db7a6 to your computer and use it in GitHub Desktop.
Read a random line from a file, supporting stdin
#!/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